且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 IGrouping 获取值

更新时间:2023-11-14 09:25:28

由于IGrouping实现了IEnumerable,所以可以使用SelectMany 将所有 IEnumerables 放回一个 IEnumerable 中:

Since IGrouping<TKey, TElement> implements IEnumerable<TElement>, you can use SelectMany to put all the IEnumerables back into one IEnumerable all together:

List<smth> list = new List<smth>();
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
IEnumerable<smth> smths = groups.SelectMany(group => group);
List<smth> newList = smths.ToList();

以下是构建/运行的示例:https://dotnetfiddle.net/DyuaaP

Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP

此解决方案的视频评论:https://youtu.be/6BsU1n1KTdo

Video commentary of this solution: https://youtu.be/6BsU1n1KTdo