【发布时间】:2008-11-06 15:17:46
【问题描述】:
假设我有一个这样的数组:
string [] Filelist = ...
我想创建一个 Linq 结果,其中每个条目在数组中的位置如下所示:
var list = from f in Filelist
select new { Index = (something), Filename = f};
第一项的索引为 0,第二项的索引为 1,依此类推
表达式 Index= 应该使用什么?
【问题讨论】:
假设我有一个这样的数组:
string [] Filelist = ...
我想创建一个 Linq 结果,其中每个条目在数组中的位置如下所示:
var list = from f in Filelist
select new { Index = (something), Filename = f};
第一项的索引为 0,第二项的索引为 1,依此类推
表达式 Index= 应该使用什么?
【问题讨论】:
不要使用查询表达式。使用the overload of Select which passes you an index:
var list = FileList.Select((file, index) => new { Index=index, Filename=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 重载。
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);
【讨论】: