如何在 Linq 结果中添加索引字段 [英] How do you add an index field to Linq results

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

问题描述

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

Lets say I have an array like this:

string [] Filelist = ...

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

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

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

第 1 项的索引为 0,第 2 项为 1,以此类推

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

我应该用什么来表达 Index= ?

What should I use for the expression Index= ?

推荐答案

不要使用查询表达式.使用重载的Select 传递给你一个索引:

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

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

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

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