0

what I want to do is to add for example class in IEnumerable after specific check

public static IEnumerable<T> GroupBy<T, O> (this IEnumerable<T> list, Func<T, O> filter)
    {
        List<IEnumerable<T>> grouped = new List<IEnumerable<T>>();

        foreach (var item in list)
        {
            foreach (var g in grouped)
            {
                foreach (var p in g)
                {
                    if (filter(p).Equals(filter(item)))
                    {
                        // Add item to g
                    }
                }
            }
        }
    }

Is something like this possible in foreach?

cassandrad
  • 3,412
  • 26
  • 50
Working Pickle
  • 122
  • 3
  • 10
  • You should check the `GroupBy` operator from *Linq*, [here](https://learn.microsoft.com/en-us/dotnet/csharp/linq/group-query-results) – VRoxa May 07 '20 at 12:50
  • 2
    Its unclear what you want to do here. Could you include an example? – RoadRunner May 07 '20 at 12:52
  • 2
    Jon Skeet has an entire blog where he implements Linq methods, including [GroupBy](https://codeblog.jonskeet.uk/2011/01/01/reimplementing-linq-to-objects-part-21-groupby/) – juharr May 07 '20 at 12:53
  • You are looping over the contents of `grouped` which has 0 items because you just initialized it, and you added nothing to it. The loop `foreach (var g in grouped)` as you wrote it will do **nothing**, it just exits, regardless of what you wrote inside of it. – Peter B May 07 '20 at 13:06
  • Does this answer your question? [What is the best way to modify a list in a 'foreach' loop?](https://stackoverflow.com/questions/759966/what-is-the-best-way-to-modify-a-list-in-a-foreach-loop) – xdtTransform May 07 '20 at 13:49

1 Answers1

0

No, that's not possible: every time you change source collection, foreach has to be started anew. You'll need to have a separate collection for intermediate accumulation, then join that collection with grouped.

Also, your algorithms doesn't work correctly: the second foreach will never start working as on the first iteration there will be no items in grouped collection. So you will just iterate list without applying any logic to its elements.

cassandrad
  • 3,412
  • 26
  • 50
  • Thanks, for answer. Yes i know at first its cleat list but i want to add elements to it and be able to group them. Basicly I'm trying to write GroupBy from Linq by myself. Now I understand its not possible as enumerator changes. Will try different algorithm. – Working Pickle May 07 '20 at 13:13