代码之家  ›  专栏  ›  技术社区  ›  leora Matt Lacey

使用LINQ转换IEnumerable集合

  •  4
  • leora Matt Lacey  · 技术社区  · 14 年前

    我有一个 IEnumerable Car 物体

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

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

    这可能吗?

    3 回复  |  直到 14 年前
        1
  •  4
  •   Sander Rijken    14 年前

    你可以通过分组来完成。看到了吗 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
        }
    }
    
        2
  •  2
  •   JaredPar    14 年前

    请尝试以下操作

    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
  •  2
  •   Matthew King    14 年前
    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> */