1

This is similar, but not quite what is being asked in this question

I have a list that I want to break into sublists, but the break occurs based on the content of an entry and not a fixed size.

Original List = [ split,1,split,2,2,split,3,3,3 ]

becomes [split,1], [split,2,2], [split,3,3,3] or [1], [2,2], [3,3,3]

Community
  • 1
  • 1
yamspog
  • 18,173
  • 17
  • 63
  • 95

2 Answers2

2

Maybe?

var list = new List<int>() { 1, 2, 0, 3, 4, 5, 0, 6 };
var subLists = list.Split(0).ToList();

IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, T divider)
{
    var temp = new List<T>();
    foreach (var item in list)
    {
        if (!item.Equals(divider))
        {
            temp.Add(item);
        }
        else
        {
            yield return temp;
            temp = new List<T>();
        }
    }

    if (temp.Count > 0) yield return temp;
}
I4V
  • 34,891
  • 6
  • 67
  • 79
0

A simple foreach is more appropriate and readable than a linq approach:

var originalList = new List<string>(){"split","1","split","2","2","split","3","3","3"};
var result = new List<List<string>>();
List<string> subList = new List<string>();
foreach(string str in originalList)
{
    if(str=="split")
    {
        subList = new List<string>();
        result.Add(subList);
    }
    subList.Add(str);
}

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939