Use the linq button group object
Suppose we have a class called Person:
<code class="language-csharp">class Person { public int PersonID; public string Car; // 将car改为Car,符合C#命名规范 }</code>
<code class="language-csharp">List<Person> persons;</code>
<code class="language-csharp">persons = new List<Person>() { new Person { PersonID = 1, Car = "Ferrari" }, new Person { PersonID = 1, Car = "BMW" }, new Person { PersonID = 2, Car = "Audi" } };</code>
<code class="language-csharp">class Result { public int PersonID; public List<string> Cars; }</code>
<code class="language-csharp">// 示例结果,实际结果由LINQ查询生成 var results = new List<Result>() { new Result { PersonID = 1, Cars = new List<string> { "Ferrari", "BMW" } }, new Result { PersonID = 2, Cars = new List<string> { "Audi" } } };</code>
<code class="language-csharp">var results = from p in persons group p.Car by p.PersonID into g select new Result { PersonID = g.Key, Cars = g.ToList() };</code>
or, you can use the lookup dictionary to achieve the same results:
<code class="language-csharp">var carsByPersonId = persons.ToLookup(p => p.PersonID, p => p.Car);</code>
<code class="language-csharp">// 这将返回一个空序列,对于查找中不存在的personId var carsForPerson = carsByPersonId[personId];</code>
The above is the detailed content of How Can I Group Objects by a Key Using LINQ in C#?. For more information, please follow other related articles on the PHP Chinese website!