假设我们有一个像这样的类:
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 post on the topic。
(我在上面将 PersonID
重命名为 PersonId
,以跟随 .NET naming conventions。)
或者,您可以使用 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];
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()/**/}
你也可以试试这个:
var results= persons.GroupBy(n => new { n.PersonId, n.car})
.Select(g => new {
g.Key.PersonId,
g.Key.car)}).ToList();
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key, Cars = g.Select(m => m.car) };
尝试
persons.GroupBy(x => x.PersonId).Select(x => x)
或者
检查是否有人在您的列表中重复尝试
persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)
我已经使用查询语法和方法语法创建了一个工作代码示例。我希望它可以帮助其他人:)
You can also run the code on .Net Fiddle here:
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
首先,设置您的关键字段。然后包括您的其他字段:
var results =
persons
.GroupBy(n => n.PersonId)
.Select(r => new Result {PersonID = r.Key, Cars = r.ToList() })
.ToList()
尝试这个 :
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];
g.Key.PersonId
? g.SelectMany
??你显然没有尝试这个。
SortedDictionary <PersonIdInt, SortedDictionary <CarNameString, CarInfoClass>>
。我可以使用 LINQ 获得的最接近的是 IEnumerable <IGrouping <PersonIdInt, Dictionary <CarNameString, PersonIdCarNameXrefClass>>>
。我结束了使用您的 for
循环方法,顺便说一句,它快了 2 倍。另外,我会使用:a) foreach
vs. for
和 b) TryGetValue
vs. ContainsKey
(均适用于 DRY 原则 - 在代码和运行时中)。
以下示例使用 GroupBy 方法返回按 PersonID
分组的对象。
var results = persons.GroupBy(x => x.PersonID)
.Select(x => (PersonID: x.Key, Cars: x.Select(p => p.car).ToList())
).ToList();
或者
var results = persons.GroupBy(
person => person.PersonID,
(key, groupPerson) => (PersonID: key, Cars: groupPerson.Select(x => x.car).ToList()));
或者
var results = from person in persons
group person by person.PersonID into groupPerson
select (PersonID: groupPerson.Key, Cars: groupPerson.Select(x => x.car).ToList());
或者您可以使用 ToLookup
,基本上 ToLookup
使用 EqualityComparer<TKey>
。默认比较键并在使用 group by 和字典时执行您应该手动执行的操作。我认为这是在内存中执行的
ILookup<int, string> results = persons.ToLookup(
person => person.PersonID,
person => person.car);
另一种方法是选择不同的 PersonId
并使用 persons
加入组:
var result =
from id in persons.Select(x => x.PersonId).Distinct()
join p2 in persons on id equals p2.PersonId into gr // apply group join here
select new
{
PersonId = id,
Cars = gr.Select(x => x.Car).ToList(),
};
或者与流畅的 API 语法相同:
var result = persons.Select(x => x.PersonId).Distinct()
.GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
{
PersonId = id,
Cars = gr.Select(x => x.Car).ToList(),
});
GroupJoin 在第一个列表(在我们的例子中是 PersonId
的列表)中生成一个条目列表,每个条目在第二个列表(persons
的列表)中都有一组连接的条目。
.GroupBy(p => new {p.Id, p.Name}, p => p, (key, g) => new { PersonId = key.Id, PersonName = key.Name, PersonCount = g.Count()})
之类的操作,您将获得所有出现的人,其 ID、名称以及每个人出现的次数。