2

我编写了以下代码以在对象列表中查找常见对象

https://dotnetfiddle.net/gCgNBf

.........................................

var query = setOfPersons
            .SelectMany(l => l.Select(l1 => l1))
            .GroupBy(p => p.Id)
            .Where(g => g.Count() == setOfPersons.Count);

之后,我需要将“查询”转换为“人员”对象列表( List )以实现其他目标。

我尝试使用“ToList()” ......但它说:

“无法将 IGrouping 转换为列表”。

有人可以帮我解决吗?

4

1 回答 1

17

查看您的代码,您似乎想要实现的是获取每个列表中存在的人员列表。如果是这样,您可以使用以下查询:

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);
}

在这里,您只从每个分组中选择一个项目,因为它们都是相同的。

于 2015-04-19T11:07:33.250 回答