【问题标题】:Convert collection of IEnumerable using LINQ使用 LINQ 转换 IEnumerable 的集合
【发布时间】:2010-09-23 11:07:56
【问题描述】:

我有一个IEnumerable Car 对象的集合

A Car 有一个属性:年份

使用 LINQ,我想找到有 > 1 辆同一年份的汽车并返回该列表。

我希望它必须返回一个列表数组,因为如果集合是:

Car 1: Year 2010
Car 2: Year 2010
Car 3: Year 2009
Car 4: Year 2009
Car 5: Year 2010
Car 6: Year 2008

我希望 2010 年的一份清单 3 和 2009 年的一份清单 2

这可能吗?

【问题讨论】:

    标签: c# linq ienumerable


    【解决方案1】:

    您可以通过分组来做到这一点。更多示例请参见hooked on linq

    var result = from car in cars
                 group car by car.year into g
                 where g.Count() > 1
                 select g
    

    现在结果是IEnumerable<IGrouping<int, Car>>,这意味着你可以这样做:

    foreach(var g in result)
    {
        int year = g.Key;
        foreach(var car in g)
        {
            // list the cars
        }
    }
    

    【讨论】:

    • 没有批评你的例子,但有时我希望 Linq 有一个 AtLeast(int count) 方法(我最终写了一个)。我知道 Group 可能在幕后返回一个 ICollection ,它在 Count() 中进行了优化,但每次我写或看到这样的东西时它仍然让我担心。
    【解决方案2】:

    试试下面的

    List<Car> list = null;
    IEnumerable<List<Car>> ret = 
        from it in list
        group it by it.Year into g
        where g.Count() > 1 
        select g.ToList();
    

    【讨论】:

      【解决方案3】:
      IEnumerable<List<Car>> carsGroupedByYear = 
          cars.GroupBy(c => c.Year) /* Groups the cars by year */
              .Where(g => g.Count() > 1) /* Only takes groups with > 1 element */
              .Select(g => g.ToList()); /* Selects each group as a List<Car> */
      

      【讨论】:

      • 这与 JaredPar 的答案完全相同
      • 流利的语法需要一些爱。
      猜你喜欢
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多