Split list of marker items using LINQ?

I have one List<T>, which is a mixture of "regular" elements and "marker" elements. I want to break it into List<List<T>>, broken into markers.

eg. given the input {a, b, M, c, d, e, f, M, g}, where 'M' is a marker element, I want to get {{a, b}, {c, d, e, f} , {g}}

It's easy to complete the task with a loop, but it seems like it should be possible to express it more compactly with LINQ, and after a little scratching my head, I just don't see how to do it. (I think LINQ-fu is not enough.)

+3
source share
2 answers

Hm ...

varSplitList = myList.Aggregate(new List<List<T>>{new List<T>()}, 
   (sl,t)=> {
      if(/*T is a marker element*/) sl.Add(new List<T>());
      else sl.Last().Add(t); 
      return sl;
   });

, , . - "", . "" ( ), , (, ) , .

, Linq:

long fact = Enumerable.Range(1,n).Aggregate(1, (f,n)=>f*n));

Enumerable.Range() 1 n. Aggregate 1 :

1 * 1 = 1 1 * 2 = 2 2 * 3 = 6 6 * 4 = 24 24 * 5 = 120...

, fact .

+5

LINQ. " LINQ", - :

var list = new List<char> {'a', 'b', 'M', 'c', 'd', 'e', 'f', 'M', 'g'};
const char marker = 'M';

var markerIndexes = list.Select((c, i) => new { c, i }).Where(z => z.c == marker).Select(z => z.i);
var split = from z in list.Select((c, i) => new { c, i })
            where z.c != marker
            group z.c by markerIndexes.Count(mi => z.i > mi) into g
            select g.ToList();
return split.ToList();
+2

Source: https://habr.com/ru/post/1766072/


All Articles