c# 通过 LINQ + 条件从数组中列出

c# list from an array via LINQ + condition

如何,使用 LINQ 我可以 select 一个数组中的最后一个元素匹配查询条件?

例如,这不起作用:

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 结果为空,因为我很可能没有正确使用 Select。 我也收到一个错误:

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

我想要 select 路径中的第二个和第三个数组,并从中创建一个列表(因为在两个 third/second 数组中,最后一个元素的变量的值为 W)

你需要 Where:

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