locked
Can I "unenumerate" a set of data? RRS feed

  • Question

  • User1642115476 posted

    Hello,

    I know that once you enumerate a linq query, you cannot enumerate it again. So if I do this:

    var d = GetData().ToList();

    d.Where(some condition).GroupBy(some property).Select(new object);

    I will get an exception.

    I'm wondering if there's a way to "un-enumerate" a set of data. Something like:

    var d = GetData().ToList();

    d.Unenumerate();

    d.Where(some condition).GroupBy(some property).Select(new object);

    ...such that this won't throw an exception.

    Tuesday, February 28, 2017 11:15 PM

All replies

  • User303363814 posted

    Can you show some actual code, tell us what you want to do and what error you are actually getting?

    Wednesday, March 1, 2017 10:21 AM
  • User-1838255255 posted

    Hi gib9898_00,

    var d = GetData().ToList();

    According to your description, ToList() method is use for convert data set inherited by IEnumerable. So you could use Linq to operate selected data. Please refer to this tutorial:

    Introduction to LINQ Queries (C#):

    https://msdn.microsoft.com/en-us/library/bb397906.aspx 

    if you un-enumerate your datasource, you will can not use linq to operate datasource.

    Do you want to show query data?

    I hope you could give us more detailed description?

    Best Regards,

    Eric Du

    Wednesday, March 1, 2017 10:36 AM
  • User1642115476 posted

    Sorry, I made a mistake in the code above. Here's how I get the error:

    var d = GetData();

    var l = d.ToList();

    var e = d.Where(some condition).GroupBy(some property).Select(new object); // <-- ERROR: "The result of a query cannot be enumerated more than once."

    Wednesday, March 1, 2017 4:22 PM
  • User475983607 posted

    The following is returning a query.

    var d = GetData();

    The following code executes the query and places the results in l.

    var l = d.ToList();

    The following throws an error because the query executed in the previous line of code.

    var e = d.Where(some condition).GroupBy(some property).Select(new object);

    Either query the list, l, or query the result of GetData()

    var e = l.Where(some condition).GroupBy(some property).Select(new object);

    or

    var e = GetDate().Where(some condition).GroupBy(some property).Select(new object);

    Please see the previously posted link for more information.

    Introduction to LINQ Queries (C#):

    https://msdn.microsoft.com/en-us/library/bb397906.aspx 

    Wednesday, March 1, 2017 7:00 PM
  • User303363814 posted

    Sorry, I made a mistake in the code above
    The solution is to use the first code you posted!

    Wednesday, March 1, 2017 8:45 PM