2013-12-10 39 views
1

我有下面的类的列表:如何选择行索引及其列表元素?

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” 
+0

是'1,2,3..'只是记录旁边的一个计数器? – christiandev

+0

@christiandev:不,否则会更容易。 – Saket

+0

我的意思是,你在** Abc **旁边应用** 1 **,因为这是**第一个记录**,** **在** Bcd **旁边,因为这是第二个**等等...? – christiandev

回答

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

列A doest包含行nos,它可以是任何整数。 – Saket

+0

@Saket编辑,谢谢! – dasblinkenlight

+0

如果我还需要选择C,该怎么办? – Saket

相关问题