【问题标题】:How can I use linq to go from an array of indices to a collection of objects?如何使用 linq 从索引数组转到对象集合?
【发布时间】:2011-09-18 03:18:14
【问题描述】:

我的标题问题有点模糊,因为很难问,但我的情况是这样的:

我有一个整数数组,它们是单独对象集合的索引。

数组如下所示:

int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };

这些索引中的每一个都对应于我拥有的集合中该索引处的一个对象。

我希望能够使用数组中的索引构建这些对象的新集合。

我将如何使用一些 LINQ 函数来做到这一点?

【问题讨论】:

    标签: c# arrays linq collections


    【解决方案1】:
    int[] indices = { 0, 2, 4, 9, 10, 11, 13 };
    string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" };
    
    IEnumerable<string> results = indices.Select(s => strings[s]);
    
    // or List<string> results = indices.Select(s => strings[s]).ToList();
    
    foreach (string result in results) // display results
    {
        Console.WriteLine(result);
    }
    

    当然,将字符串等更改为您的对象集合。

    【讨论】:

      【解决方案2】:

      这样的事情应该可以工作:

      List<int> items = Enumerable.Range(1,100).ToList();
      int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };
      var selectedItems = indices.Select( x => items[x]).ToList();
      

      基本上,对于索引集合中的每个索引,您都使用索引器将其投影到 items 集合中的相应项目(无论这些项目是什么类型)。

      如果您的目标集合只是一个IEnumerable&lt;SomeType&gt;,那么您也可以使用ElementAt() 而不是索引器:

      var selectedItems = indices.Select(x => items.ElementAt(x)).ToList();
      

      【讨论】:

      • 感谢您的回复。我希望我能接受多个答案,有时我会因为无法接受每一个有效的答案而感到难过。 :(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多