简体   繁体   中英

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. 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> . I need to convert it back to a IEnumerable<MyClass> , and my constraint is that I cannot call ToList() otherwise I get an OutOfMemoryException.

Any idea ?

GroupBy returns IEnumerable<IGrouping<TKey, TSource>> , which you could flatten as:

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 :

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>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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