【问题标题】:How do you add an index field to Linq results如何将索引字段添加到 Linq 结果
【发布时间】:2008-11-06 15:17:46
【问题描述】:

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

string [] Filelist = ...

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

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

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

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

【问题讨论】:

    标签: c# linq


    【解决方案1】:

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

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

    【讨论】:

    • 如何在sql语法中做到这一点?
    • @toddmo:“在 sql 语法中”是指“使用 LINQ 查询表达式”吗?如果是这样,你不能。如果您的意思是“在 SQL 本身中”,那么我不知道 - 我怀疑有不可移植的方法。
    • 我想通了,谢谢。我的意思是:(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 重载。
    【解决方案2】:
    string[] values = { "a", "b", "c" };
    int i = 0;
    var t = (from v in values
    select new { Index = i++, Value = v}).ToList();
    

    【讨论】:

    • 为什么不使用框架提供的版本而不是麻烦?
    • 为什么不呢!?有用。您可以通过这种方式完全控制。我自己可能不会这样做,但这是被问到的问题。
    • 但是如果你运行/调用/触发查询两次,你会得到不同的 ID - 我不介意最后是否有一个 ToArray 来突出这个......
    • 另外,通过可以应用于 linq 的新并行,您可以让它们乱序,甚至使用相同的数字。哎哟!
    • 它使用替代语法,不需要 lambda。正如我所说,我不会推荐这种方法,只是提供一个替代答案。值得深思。
    【解决方案3】:

    无法使用纯 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多