【发布时间】:2015-02-03 01:29:57
【问题描述】:
如何使用 LINQ 选择一个数组中最后一个与查询条件匹配的元素?
例如,这不起作用:
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 显示为 null,因为我很可能没有正确使用 Select。 我也收到一个错误:
CS 0039: Cannot convert type 'bool' to System.Collections.Generic.List<Node[]> via a built-in conversion
我想从路径中选择第二个和第三个数组,并从中创建一个列表(因为在第三个/第二个数组中,最后一个元素的变量的值都是 W)
【问题讨论】:
-
@GrantWinney,这是一个类,但在这种情况下,我使用字符串只是为了能够提供一些东西。