【问题标题】:c# and LINQ - convert IGrouping to Listc# 和 LINQ - 将 IGrouping 转换为 List
【发布时间】:2015-06-26 01:19:13
【问题描述】:

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

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 转换为 List"。

有人可以帮我解决吗?

【问题讨论】:

标签: c# linq list igrouping


【解决方案1】:

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

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

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

【讨论】:

  • 我不知道该怎么感谢你!你救了我的一天!感谢一百万!
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多