Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ-具有元素计数的双重分组_C#_Sql_Linq - Fatal编程技术网

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

C# LINQ-具有元素计数的双重分组,c#,sql,linq,C#,Sql,Linq,例如,我有以下PlaneSGrow对象列表 public class PlanesLogRow { public DateTime ArriveDate; public string Origin; public string Destination; } 需要获取所有机场的列表(起点+终点)。Distinct() 需要计算每个机场的“到达机场”和“离开机场”计数 我需要创建一个LINQ字符串元组,如 获取所有机场的列表不是问题,但不确定在按不同参数进行双重分组的情况下

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

public class PlanesLogRow
{
    public DateTime ArriveDate;
    public string Origin;
    public string Destination;
}
  • 需要获取所有机场的列表
    (起点+终点)。Distinct()

  • 需要计算每个机场的“到达机场”和“离开机场”计数

  • 我需要创建一个LINQ字符串元组,如


    获取所有机场的列表不是问题,但不确定在按不同参数进行双重分组的情况下如何实现这一点

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

    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" },
    };
    

    更新:此查询将使用实体框架。生成的SQL将是巨大而可怕的。

    非常感谢,您太棒了!
    [
      { "Airport": "Minsk", "AsOriginCount": 1, "AsDestinationCount": 2 },
      { "Airport": "London", "AsOriginCount": 1, "AsDestinationCount": 2 },
      { "Airport": "Barcelona", "AsOriginCount": 2, "AsDestinationCount": 0 },
      { "Airport": "Rome", "AsOriginCount": 1, "AsDestinationCount": 1 }
    ]