假设我们有这样的课程:
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 帖子。
(我在上面将
PersonID
重命名为 PersonId
,以遵循 .NET 命名约定,该约定在“大写复合词和常用术语”部分中专门指出了这一点。)
或者,您可以使用
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)
我使用查询语法和方法语法创建了一个工作代码示例。我希望它能帮助其他人:)
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 法拉利 宝马 2 奥迪 ------------ 1 法拉利 宝马 2 奥迪
首先,设置您的关键字段。然后包括您的其他字段:
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];
以下示例使用 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(),
};
或者与 Fluent 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
列表)中都有一组连接条目。
ATL Black Trucks 为许多活动提供豪华轿车租赁服务。我们的专业运输专家随时指导您为您的特殊活动选择合适的车辆。请阅读以下我们提供服务的活动! 乘坐豪华车