Search code examples
c#arrayslinqlistdelta

c# list from an array via LINQ + condition


How, using LINQ can I select an array the last element in which matches the query condition?

For example, this didn't work:

public class Node{
  public var nodeVar;

    public Node(var arg){     //constructor of node
        this.nodeVar = arg;
    }
}   //end of class


Node[][] path = new Node[3][]; //a jagged array from which to select the required arrays
path[0] = new Node[]{ new Node("A"), new Node("B"), new Node("C") };
path[1] = new Node[]{ new Node("D"), new Node("E"), new Node("W") };
path[2] = new Node[]{ new Node("G"), new Node("W") };

//trying to initialize a list of Node arrays using LINQ:
List<Node[]> thirdArray = path.Select(o => (o.Last().nodeVar == "W") as List<Node[]> ).ToList()

thirdArray comes out as null, since I am most likely not using Select properly. I am also getting an error:

CS 0039: Cannot convert type 'bool' to System.Collections.Generic.List<Node[]> via a built-in conversion

I would want to select the second and third arrays from the path, and make a list from them (since in both third/second arrays, the last element's variable has a value of W)


Solution

  • You need a Where:

    var thirdArray = path.Where(o => o.Last().nodeVar=="W"   ).ToList();