假设我有这样一个数组:
string [] Filelist = ...
我想创建一个 Linq 查询结果,每个条目都有它在数组中的位置,像这样:var list = from f in Filelist
select new { Index = (something), Filename = f};
第一个项目索引应为0,第二个应为1,以此类推。
我该使用什么表达式来表示 Index = ?
不要使用查询表达式。 使用 传递索引的重载 Select
:
var list = FileList.Select((file, index) => new { Index=index, Filename=file });
string[] values = { "a", "b", "c" };
int i = 0;
var t = (from v in values
select new { Index = i++, Value = v}).ToList();
使用纯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);
(from GHCOPPADriverType driver in policy.Drivers from GHCOPPADriverHistoryType driverHistory in driver.Rating_DrivingHistory select (driver: driver, history: driverHistory)).Select((t,i) => new DriverHistoryModel(t.history) { DriverId = t.driver.Id, Sequence = i + 1 });
。所以,我必须离开查询表达式才能使用Select
重载。 - toddmo