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]

2
  • 1
    What do you want it to break on? Commented Aug 9, 2013 at 21:55
  • 1
    What's the type of your list? object? Commented Aug 9, 2013 at 22:00

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.