提问



我们假设我们有类似的课程


class Person { 
    internal int PersonID; 
    internal string car  ; 
}


现在我列出了这个类:List<Person> persons;


现在,此列表可以具有多个具有相同PersonID的实例,例如:


persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 


有没有办法按personID分组,并获得他所有车辆的清单?


例如,预期结果将是


class Result { 
   int PersonID;
   List<string> cars; 
}


分组后,我会得到:


results[0].PersonID = 1; 
List<string> cars = results[0].cars; 

result[1].PersonID = 2; 
List<string> cars = result[1].cars;


从我到目前为止所做的:


var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, // this is where I am not sure what to do


有人可以指出我正确的方向吗?

最佳参考


绝对 - 你基本上想要:


var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.ToList() };


或者作为非查询表达式:


var results = persons.GroupBy(
    p => p.PersonId, 
    p => p.car,
    (key, g) => new { PersonId = key, Cars = g.ToList() });


基本上,组的内容(当作为IEnumerable<T>视图时)是给定键存在的投影(在这种情况下为p.car)中的任何值的序列。


有关GroupBy如何工作的更多信息,请参阅我关于该主题的Edulinq帖子。[27]


(我在上面已经将PersonID重命名为PersonId,以遵循.NET命名约定。)[28]


或者,您可以使用Lookup:


var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);


然后,您可以非常轻松地为每个人获取汽车:


// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];

其它参考1


var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

其它参考2


var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, Cars = g.Select(m => m.car) };

其它参考3


你也可以尝试这个。


var results= persons.GroupBy(n => new { n.PersonId, n.car})
                .Select(g => new {
                               g.Key.PersonId,
                               g.Key.car)}).ToList();

其它参考4


尝试


persons.GroupBy(x => x.PersonId).Select(x => x)


要么


检查是否有人在您的列表中重复尝试


persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)

其它参考5


我已经使用查询语法和方法语法创建了一个工作代码示例。我希望它可以帮助其他人:)


您也可以在.Net小提琴上运行代码:[29]


using System;
using System.Linq;
using System.Collections.Generic;

class Person
{ 
    public int PersonId; 
    public string car  ; 
}

class Result
{ 
   public int PersonId;
   public List<string> Cars; 
}

public class Program
{
    public static void Main()
    {
        List<Person> persons = new List<Person>()
        {
            new Person { PersonId = 1, car = "Ferrari" },
            new Person { PersonId = 1, car = "BMW" },
            new Person { PersonId = 2, car = "Audi"}
        };

        //With Query Syntax

        List<Result> results1 = (
            from p in persons
            group p by p.PersonId into g
            select new Result()
                {
                    PersonId = g.Key, 
                    Cars = g.Select(c => c.car).ToList()
                }
            ).ToList();

        foreach (Result item in results1)
        {
            Console.WriteLine(item.PersonId);
            foreach(string car in item.Cars)
            {
                Console.WriteLine(car);
            }
        }

        Console.WriteLine("-----------");

        //Method Syntax

        List<Result> results2 = persons
            .GroupBy(p => p.PersonId, 
                     (k, c) => new Result()
                             {
                                 PersonId = k,
                                 Cars = c.Select(cs => cs.car).ToList()
                             }
                    ).ToList();

        foreach (Result item in results2)
        {
            Console.WriteLine(item.PersonId);
            foreach(string car in item.Cars)
            {
                Console.WriteLine(car);
            }
        }
    }
}


结果如下:


1
Ferrari
BMW
2
Audi
-----------
1
Ferrari
BMW
2
Audi


其它参考6


尝试这个 :


var results= persons.GroupBy(n => n.PersonId)
            .Select(g => new {
                           PersonId=g.Key,
                           Cars=g.Select(p=>p.car).ToList())}).ToList();


但是在性能方面,以下实践在内存使用方面更好,更优化(当我们的数组包含更多的项目,如数百万)时:


var carDic=new Dictionary<int,List<string>>();
for(int i=0;i<persons.length;i++)
{
   var person=persons[i];
   if(carDic.ContainsKey(person.PersonId))
   {
        carDic[person.PersonId].Add(person.car);
   }
   else
   {
        carDic[person.PersonId]=new List<string>(){person.car};
   }
}
//returns the list of cars for PersonId 1
var carList=carDic[1];