我有一个返回MyObject列表的linq查询。我想在MyObject中添加一个名为TheIndex的属性,它包含序列中项目的纵坐标。
换句话说,我需要这样的东西:
var TheResult = from d in MyDataContext
where.....
select new MyObject
{
Property1 = d.whatever,
TheIndex = ?
}
查询返回MyObject列表,我希望列表中的每个项目都包含索引作为其属性之一。
感谢。
答案 0 :(得分:15)
一旦您离开查询语法,您将找到一个Select重载,它为您提供所需的索引。
var result = MyDataContext
.Where(d => d.Prop == "A")
.AsEnumerable()
.Select((d, i) =>
new MyObject() {
Property1 = d.whatever,
TheIndex = i
});