代码之家  ›  专栏  ›  技术社区  ›  Keltex

如何将索引字段添加到Linq结果

  •  48
  • Keltex  · 技术社区  · 17 年前

    假设我有这样一个数组:

    string [] Filelist = ...
    

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

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

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

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

    3 回复  |  直到 17 年前
        1
  •  132
  •   patridge jonathanpeppers    14 年前

    不要使用查询表达式。使用 the overload of Select which passes you an index

    var list = FileList.Select((file, index) => new { Index=index, Filename=file });
    
        2
  •  1
  •   GeekyMonkey    14 年前
    string[] values = { "a", "b", "c" };
    int i = 0;
    var t = (from v in values
    select new { Index = i++, Value = v}).ToList();
    
        3
  •  1
  •   Artemious    8 年前

    无法获取索引 使用纯LINQ查询表达式(具有 from.. where.. select..

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