如何选择行索引及其列表元素?

时间:2013-12-10 13:45:01

标签: 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'

我想要一个linq查询,它会给我这样的输出:

1   “Abc”
2   “Bcd”
3   “Cde”
4   “Def”
5   “Efg”

1 个答案:

答案 0 :(得分:3)

您可以将new与匿名类一起使用以获取投影;使用the override of Select that gives you the item number to produce the row number,如下所示:

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);
}