如何为Linq结果添加索引字段

时间:2008-11-06 15:17:46

标签: c# linq

假设我有一个这样的数组:

string [] Filelist = ...

我想创建一个Linq结果,其中每个条目在数组中的位置如下:

var list = from f in Filelist
    select new { Index = (something), Filename = f};

第一项为0,第二项为1,等等

我应该将什么用于表达式索引=?

3 个答案:

答案 0 :(得分:120)

不要使用查询表达式。使用the overload of Select which passes you an index

var list = FileList.Select((file, index) => new { Index=index, Filename=file });

答案 1 :(得分:0)

string[] values = { "a", "b", "c" };
int i = 0;
var t = (from v in values
select new { Index = i++, Value = v}).ToList();

答案 2 :(得分:0)

使用纯LINQ查询表达式(具有from.. where.. select..子句的表达式)无法获取索引

然而,这并不意味着你必须完全放弃这种LINQ查询风格。

您只需退出LINQ查询表达式并使用.Select(item, index)方法重载。

var newestExistingFilesWithIndexes = 
    (from f in Filelist
     // we love LINQ query expressions
     where f.Exists
     // and we use it anywhere possible
     orderby f.LastModified descending
     select f)
     // but sometimes we have to get out and use LINQ extension methods
    .Select((f, index) => new { Index = index, Filename = f.Fullname});

或者假设,您需要根据项目索引过滤列表...

var newestExistingFilesOnlyEvenIndexes = 
     // use the Select method overload to get the index
    (from f in Filelist.Select((file, index) => new { file, index })
     // only take item with an even index
     where f.index % 2 == 0
     where f.file.Exists
     orderby f.file.LastModified descending
     select f.file);