Linq 如何选择列表中的行索引及其元素?
我有以下班级的名单:Linq 如何选择列表中的行索引及其元素?,linq,c#-4.0,Linq,C# 4.0,我有以下班级的名单: Class Test { int A; String B; Char C; } List<Test> obj: 10 “Abc” 'a' 29 “Bcd” 'b' 36 “Cde” 'c' 45 “Def” 'd' 51 “Efg” 'e' 您可以对匿名类使用new,以获得投影;像这样使用: 1 “Abc” 2 “Bcd” 3 “Cde” 4 “Def” 5 “Efg” var projection =
Class Test
{
int A;
String B;
Char C;
}
List<Test> obj:
10 “Abc” 'a'
29 “Bcd” 'b'
36 “Cde” 'c'
45 “Def” 'd'
51 “Efg” 'e'
您可以对匿名类使用
new
,以获得投影;像这样使用:
1 “Abc”
2 “Bcd”
3 “Cde”
4 “Def”
5 “Efg”
var projection = obj.Select((o,i) => new {Index = i+1, Value=B});
foreach (var item in projection) {
Console.WriteLine("{0} “{1}”", item.Index, item.Value);
}
1,2,3..
只是记录旁边的一个计数器吗?@christiandev:不,否则会更容易。我的意思是,你是在Abc旁边应用1作为第一条记录,在Bcd旁边应用2作为第二条记录等等?@christiandev:不是这样的。第一列可以包含任何整数。A列不包含行号,它可以是任何整数。如果我也必须选择C怎么办?new{Index=i+1,Value=B,AnotherValue=C}
或new{Index=i+1,Value=B+“”+C}
@Matten:谢谢!