我编写了以下代码来查找对象列表中的公共对象
https://dotnetfiddle.net/gCgNBf
..............................
var query = setOfPersons
.SelectMany(l => l.Select(l1 => l1))
.GroupBy(p => p.Id)
.Where(g => g.Count() == setOfPersons.Count);
之后,我需要将“查询”转换为“人物”对象(列表)列表以实现其他目的。
我尝试使用“ToList()” ......但它说:
“无法将IGrouping转换为列表”。
有人可以帮我解决吗?
答案 0 :(得分:9)
查看您的代码,您尝试实现的目标似乎是获取每个列表中存在的人员列表。如果是这样,您可以使用以下查询:
var query = setOfPersons
.SelectMany(l => l.Select(l1 => l1))
.GroupBy(p => p.Id)
.Where(g => g.Count() == setOfPersons.Count)
.Select(x=>x.First()) // Select first person from the grouping - they all are identical
.ToList();
Console.WriteLine("These people appears in all set:");
foreach (var a in query)
{
Console.WriteLine("Id: {0} Name: {1}", a.Id, a.Name);
}
在这里,您只从每个分组中选择一个项目,因为它们都是相同的。