【问题标题】:iteration fails over sorted array迭代失败排序数组
【发布时间】:2012-08-24 19:09:36
【问题描述】:

我有以下方法对绑定源索引列表进行排序并将其对应的对象放入数组中。我也尝试过使用Array.Sort(),但都不起作用,foreach 循环中的代码永远不会被调用。我测试了变量int[] indices既不为空也不为空。

internal void Foo(int[] indices)
{
    var bar = new Object[indices.length];
    int i = 0;
    foreach (int index in indices.OrderBy(x => x))
    {
        // this block never gets called
        bar[i] = BindingSource[index];
        i++;
    }
}

【问题讨论】:

  • 你可以把它变成一个 LINQ “oneliner”:var bar = (from i in indices order by i select BindingSource[i]).ToArray() - 也许这会清除错误。 (也就是说,我猜原因是 indices 是空的,只是可能不在您调试的调用中。)
  • 你如何验证它永远不会被调用?在调试器中?
  • 使用您的代码,只要索引包含至少一个元素,我就可以在foreach 中进行跟踪。如果问题仍然存在,则说明问题中没有包含某些内容。

标签: c# .net arrays loops


【解决方案1】:

你可以试试这个:

var bar = indices.OrderBy(x => x).Select(x => BindingSource[x]).ToArray();

但我认为你的代码应该可以工作,尽管我认为你可以使用 for 循环而不是 foreach 来改进它。

internal void Foo(int[] indices)
{
    var bar = new Object[indices.Length];
    indices = indices.OrderBy(x => x);
    for(int i = 0; i < indices.Length; i++)
        bar[i] = BindingSource[indices[i]];    
}

另外,你应该确定indices.Length 不等于0,所以我认为索引是空的。

PS : C# 区分大小写,因此代码中的 indices.length 应为 indices.Length

【讨论】:

    【解决方案2】:

    问题是OrderBy 没有返回排序后的数组,正如我所假设的那样。以下是我的解决方案。

    internal void Foo(int[] indices)
    {
        var bar = new Object[indices.Length];
        int i = 0;
        indices = indices.OrderBy(x => x).ToArray();
        foreach (int index in indices)
        {
            // now this block gets called
            bar[i] = BindingSource[index];
            i++;
        }
    }
    

    【讨论】:

    • 现在,ToArray() 只需要内存和时间。把它排除在外,唯一的区别是更好的性能。
    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 2012-07-22
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2016-08-06
    相关资源
    最近更新 更多