简体   繁体   English

将集合从IGrouping转换为IEnumerable

[英]Cast collection from IGrouping to IEnumerable

I have a very large collection consistings in my millions of elements. 我有数百万个元素的大量收藏。 I need to keep everything as IEnumerable otherwise I get an OutOfMemoryException. 我需要将所有内容都保持为IEnumerable,否则会收到OutOfMemoryException。 My problem is that I have to do some grouping like that : 我的问题是我必须像这样进行分组:

IEnumerable<MyClass> mycollection = dao.RetrieveBigCollection-();
var mycollection = mycollection.GroupBy(x => x.Date1);

And later in the program, the collection will be fetched by some library which uses reflection. 之后在程序中,将通过使用反射的某些库来获取该集合。 The problem is that after grouping the collection is of type IGrouping, and this library expects a IEnumerable<MyClass> . 问题在于,在对集合进行分组之后,该集合的类型为IGrouping,并且此库期望使用IEnumerable<MyClass> I need to convert it back to a IEnumerable<MyClass> , and my constraint is that I cannot call ToList() otherwise I get an OutOfMemoryException. 我需要将其转换回IEnumerable<MyClass> ,并且我的约束是我无法调用ToList(),否则会收到OutOfMemoryException。

Any idea ? 任何想法 ?

GroupBy returns IEnumerable<IGrouping<TKey, TSource>> , which you could flatten as: GroupBy返回IEnumerable<IGrouping<TKey, TSource>> ,您可以将其展平为:

groupings.SelectMany(x => x);

However, you will still run into memory issues, because groupings internally keep a collection in memory, so your whole enumerable will be pulled into memory anyway. 但是,您仍然会遇到内存问题,因为分组在内​​部将一个集合保存在内存中,因此无论如何您的整个可枚举对象都会被拉到内存中。

Well, it is a lot late, but for others that may come looking, you should be able to use Select : 好吧,已经很晚了,但是对于其他可能会寻找的人,您应该可以使用Select

IEnumerable<MyClass> mycollection = dao.RetrieveBigCollection-();
var mycollection = mycollection.GroupBy(x => x.Date1)
                               .Select(xg => xg.Select(x => x));

The result will be an IEnumerable<IEnumerable<MyClass>> . 结果将是IEnumerable<IEnumerable<MyClass>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM