开发者

adding index to linq query result

I have a linq query that returns a list of MyObject. I'd like to add a property to MyObject called TheIndex and that contains the ordinate of the item in the sequence.

In other words, I need something like this:

var TheResult = from d in MyDataContext
                where.....
                select new MyObject
                {
                   Property1 = d.whatever,

    开发者_开发百科               TheIndex = ?

                 }

The query returns a list of MyObject and I'd like each item in the list to contain the index as one of its property.

Thanks.


Once you get away from the query syntax, you'll find a Select overload that gives you the index you're looking for.

var result = MyDataContext
   .Where(d => d.Prop == "A")
   .AsEnumerable()
   .Select((d, i) => 
      new MyObject() {
         Property1 = d.whatever,
         TheIndex = i
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜