Home > Net >  C# Splitting a list based on items
C# Splitting a list based on items

Time:01-10

I have a list with following items (lets call it 'main list'):

[1,2,2,3,1,2,3,4,4,1,2,2]

My goal is to split it into smaller lists that will contain '1' and the following numbers (until the next '1' occurs). The end result should look like this:

[1,2,2,3]
[1,2,3,4,4]
[1,2,2]

Some additional info:

  1. small lists can be of different lengths
  2. the main list always starts with '1' (so you don't have to look for the beginning)
  3. the elements of the main list and smaller lists are strings!
  4. the number of smaller lists depends on the number of '1' in the main list

Basically I need to split a list of strings to smaller lists of strings.

The first idea that came to my mind was to create a ('final') list containing smaller lists, so I created a loop:

List<string> templist = new List<string>();
List<List<string> final = new List<List<string>();

foreach (string log in mainlist)
{
 if (log != '1')
    {
    templist.Add(log);
    }
 else
    {
     final.add(templist);
     templist.Clear();
     templist.Add(log)}
    }
final.add(templog);

it seems to work but I get a list with duplicates: [[1,2,2],[1,2,2],[1,2,2]]

CodePudding user response:

you can do this.

check for 1 and initialize the current list with default item 1 (add the current list to the final list in this step as well)

and if not one then keep on adding the items to the current list.

List<string> currentList = null;
List<string> mainList = new List<string> { "1", "2", "2", "3", "1", "2", "3", "4", "4", "1", "2", "2" };
List<List<string>> finalList = new List<List<string>>();

            
foreach (string item in mainList)
{
    if (item == "1")
    {
        currentList = new List<string>() { item };
        finalList.Add(currentList);
    }
    else
    {
        currentList.Add(item);
    }
}

CodePudding user response:

Can be:

 else
 {
     templist = new List<string>(){log};
     final.add(templist);
 }

CodePudding user response:

You can find the index of all occurrences of 1. Then according to these indexes and using the two functions Take() and Skip() to separate the lists..

List<string> mainlist = new List<string>{"1","2","2","3","1","2","3","4","4","1","2","2"};
List<List<string>> final = new List<List<string>>();

var numberOfList = mainlist.Select((item, index) => new {val = item,ind = index})
                                    .Where(item => item.val == "1").ToList();


for(int i = 0; i<numberOfList.Count;i  )
{
    if(i == numberOfList.Count-1)
        final.Add(mainlist.Skip(numberOfList[i].ind)
                          .Take(mainlist.Count - numberOfList[i].ind).ToList());
    else
        final.Add(mainlist.Skip(numberOfList[i].ind)
                          .Take(numberOfList[i   1].ind - numberOfList[i].ind).ToList());
}

result:

[1,2,2,3]

[1,2,3,4,4]

[1,2,2]

  • Related