C# 如何在 Linq 结果中添加索引字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/269058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:53:09  来源:igfitidea点击:

How do you add an index field to Linq results

c#linq

提问by Keltex

Lets say I have an array like this:

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

string [] Filelist = ...

I want to create an Linq result where each entry has it's position in the array like this:

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

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

Index to be 0 for the 1st item, 1 for the 2nd, etc.

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

What should I use for the expression Index= ?

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

采纳答案by Jon Skeet

Don't use a query expression. Use the overload of Selectwhich passes you an index:

不要使用查询表达式。使用传递给您索引的重载Select

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

回答by GeekyMonkey

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

回答by Artemious

You cannot get an indexusing pure LINQ query expressions (those with from.. where.. select..clauses).

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

However, this doesn't mean you have to completely give up on this LINQ query style.

但是,这并不意味着您必须完全放弃这种 LINQ 查询样式。

You just have to get out of the LINQ query expressionand use a .Select(item, index)method overload.

您只需要退出 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});

or suppose, you need to filter a list based on item index ...

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

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