【问题标题】:Using Linq to find array with the largest length使用 Linq 查找长度最大的数组
【发布时间】:2014-03-17 09:09:07
【问题描述】:

我需要在数组列表中找到最大的数组。 使用基本技术,我可以做到这一点

        List<int[]> intArrayList;
        ...
        int largestArrayIndex = 0;
        for (int i = 1; i < intArrayList.Count; i++)
        {
            if (intArrayList[largestArrayIndex].Length < 
                intArrayList[i].Length)
            {
                largestArrayIndex = i;
            }
        }

但是,我很好奇是否有更简洁的方法来使用 Linq 执行此操作? 而且,两者之间会有性能差异吗?

编辑:我想要最大的数组。所以,如果我有一个 { int[5], int[7], int[9], int[3] } 的列表,我想要索引或引用 int[9] 数组。

谢谢。

【问题讨论】:

  • 你想知道最大长度,还是想返回最长的数组?
  • 伙计们来吧。他显然是在说他想在数组列表中找到最大的数组(元素最多的那个)。他的例子找到了最大数组的索引。 (授予..标题有点误导)

标签: c# linq


【解决方案1】:

你可以这样做:

var longest = intArrayList.Aggregate((i1,i2) => i1.Length > i2.Length ? i1 : i2);

性能方面,它只会对列表进行一次迭代,所以我会说它与您的代码几乎相同。

编辑:只是想澄清一下我的代码返回的是最长的数组,而不是最长的长度。

干杯

【讨论】:

    【解决方案2】:

    另一种方式:

    int[] longestArray =  intArrayList.OrderBy(x => x.Length).Last();
    

    它返回最长的数组。如果需要最长数组的索引,那么:

    int index = intArrayList.Select((x,i) => new {Length = x.Length, Index = i}).OrderBy(x => x.Length).Last().Index;
    

    【讨论】:

    • 很遗憾,它无法编译。
    • 已修复。谢谢你,@Dmitry
    【解决方案3】:

    我相信原来的方法是好的。下面的代码应该做同样的事情:

    int maxLen = int.MinValue;
    int maxLenIndex = intArrayList.SelectMany((array, index) => array.Length > maxLen && ((maxLen = array.Length) > int.MinValue) ? new[] { index } : new int[0]).Last();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2011-07-16
      相关资源
      最近更新 更多