添加索引LINQ查询结果 [英] adding index to linq query result

查看:470
本文介绍了添加索引LINQ查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ查询,返回MyObject的列表。我想补充一个属性为myObject称为TheIndex以及包含该项目的序列中的坐标。

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 = ?

                 }

该查询返回MyObject的名单,我想在列表中的每个项目包含索引作为其属性之一。

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.

感谢。

推荐答案

一旦你得到的查询语法的时候,你会发现一个选择的过载,让你你要找的索引。

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

这篇关于添加索引LINQ查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆