Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting List based on element variable and element position

Tags:

c#

list

split

linq

hey I'm trying to split a list based on if a bool of the element is true or not. but each time it has passed some true's and encounters a false i want it also to start a new list with the all the false until it encounters true again and so on. so basicly grouping sequences of falses and trues

public void SortWalls()
{
    List<Node> innerWallNodes;
    foreach(Wall w in walls)
    {
        WallAxis ax = w.axis;
        innerWallNodes = new List<Node>();
        for(int i=w.wallNodes.Count-1; i>=0; i--)
        {
            if(w.wallNodes[i].markedForDoor)
            {
                //split wall!!
                innerWallNodes.Add(w.wallNodes[i]);
                w.wallNodes.RemoveAt(i);
            }
        }
        if(innerWallNodes.Count > 0)
        {
            Wall wall = new Wall(innerWallNodes, ax);
            innerWalls.Add(wall);
        }
    }
}

i did it like this and then build a mesh based on the first and last element of a List. but since there are many scenarios where the innerWallNodes could be somewhere in the middle of the list that get "cut out" and so my remaining "outer wall" would still have the same node index in my grid for the first and last in it's list, still overdrawing my "inner wall"

so lets say every node !markedForDoor is 0 and a every node markedForDoor is 1 and they order something like below in my list. like this:

|000|11111|00000|11|000| how would i get a list for every between |...| ?

how do i do this in a simple way. I thought Linq would have something for this but can't find anything.

like image 871
Rottjung Avatar asked Jun 27 '26 00:06

Rottjung


2 Answers

Linq won't help. Here is the code:

List<List<YouObjectType>> SplitList(List<YourObjectType> listToSplit) {
    List<List<YouObjectType>> listOfLists = new List<List<YourObjectType>>();
    List<YourObjectType> tmp = new List<YourObjectType>();
    foreach(YourObjectType item in listToSplit) {
        if (tmp.Count > 0
            && tmp[tmp.Count - 1] != item) {
            // Compare you items here as you wish, 
            // I'm not sure what kind of objects
            // and what kind of comparison you are going to use
            listOfLists.Add(tmp);
            tmp = new List<YourObjectType>();
        }
        tmp.Add(item);
    }
    if (tmp.Count > 0) {
        listOfLists.Add(tmp);
    }
    return listOfLists;
}
like image 57
Alex Butenko Avatar answered Jun 29 '26 15:06

Alex Butenko


Here is a simple way of doing that (no Linq)

List<Node> input = ...;
var output = new List<List<Node>>();
for (int end = 0; end < input.Count; )
{
    int start = end;
    while (++end < input.Count && input[end].markedForDoor == input[start].markedForDoor) { }
    output.Add(input.GetRange(start, end - start));
}
like image 23
Ivan Stoev Avatar answered Jun 29 '26 13:06

Ivan Stoev