LINQ - 具有元素计数的双重分组

时间:2017-03-29 16:32:10

标签: c# sql linq

例如,我有以下PlanesLogRow对象列表

public class PlanesLogRow
{
    public DateTime ArriveDate;
    public string Origin;
    public string Destination;
}
  1. 需要获取所有机场的列表(Origin + Destination).Distinct()

  2. 每个机场需要计算一次#34;到达机场"和#34;离开机场"计数。

  3. 我需要创建一个像<airport, AsOriginCount(arrivedToCount), AsDestinationCount(LeftFromCount)>

    这样的LINQ字符串元组

    获取所有机场的列表并不是一个问题,但不确定如何通过不同的参数进行这种双重分组

1 个答案:

答案 0 :(得分:3)

如果您有飞机列表,则可以将每个飞机对象投影为两个匿名对象 - 一个用于目标,一个用于原点。然后按机场对这些匿名对象进行分组并计算总数:

planes.SelectMany(p => new[] { 
         new { Airport = p.origin, IsOrigin = true },
         new { Airport = p.destination, IsOrigin = false }
       })
       .GroupBy(x => x.Airport)
       .Select(g => new {
           Airport = g.Key,
           AsOriginCount = g.Count(x => x.IsOrigin),
           AsDestinationCount = g.Count(x => !x.IsOrigin)
       })

对于特定的飞机:

var planes = new List<Plane> {
    new Plane { Origin = "Minsk", Destination = "London" },
    new Plane { Origin = "Barcelona", Destination = "Minsk" },
    new Plane { Origin = "Rome", Destination = "Minsk" },
    new Plane { Origin = "Barcelona", Destination = "London" },
    new Plane { Origin = "London", Destination = "Rome" },
};

输出将是:

[
  { "Airport": "Minsk", "AsOriginCount": 1, "AsDestinationCount": 2 },
  { "Airport": "London", "AsOriginCount": 1, "AsDestinationCount": 2 },
  { "Airport": "Barcelona", "AsOriginCount": 2, "AsDestinationCount": 0 },
  { "Airport": "Rome", "AsOriginCount": 1, "AsDestinationCount": 1 }
]

更新:此查询将与Entity Framework一起使用。生成的SQL会很大而且很可怕。