首页> C#>如何为Linq结果添加索引字段

可以说我有一个像这样的数组:

string [] Filelist = ...

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

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

第一项的索引为0,第二项的索引为1,依此类推。

表达式Index =应该使用什么?

Keltex asked 2020-01-14T12:14:57Z
3个解决方案
122 votes

不要使用查询表达式。 使用Select的重载为您传递一个索引:

var list = FileList.Select((file, index) => new { Index=index, Filename=file });
Jon Skeet answered 2020-01-14T12:15:38Z
0 votes
string[] values = { "a", "b", "c" };
int i = 0;
var t = (from v in values
select new { Index = i++, Value = v}).ToList();
GeekyMonkey answered 2020-01-14T12:15:54Z
0 votes

您不能使用纯LINQ查询表达式(带有.Select(item, index)子句的表达式)获得索引。

但是,这并不意味着您必须完全放弃这种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);
Artemious answered 2020-01-14T12:16:28Z
translate from https://stackoverflow.com:/questions/269058/how-do-you-add-an-index-field-to-linq-results