【问题标题】:Is there any compact and elegant way in C# to simultaneously iterate through two lists? [duplicate]C# 中是否有任何紧凑而优雅的方式可以同时遍历两个列表? [复制]
【发布时间】:2016-07-21 18:07:16
【问题描述】:

所以我有几段代码可以用来做类似的事情

        List<ParameterInfo> theseParams = this.Action.GetParameters().OrderBy(p => p.Name).ToList(),
                            otherParams = other.Action.GetParameters().OrderBy(p => p.Name).ToList();
        if(theseParams.Count != otherParams.Count)
            return false;
        for(int i = 0; i < theseParams.Count; ++i)
        {
            ParameterInfo thisParam = theseParams[i],
                          otherParam = otherParams[i];
            if(thisParam.Name != otherParam.Name)
                return false;
        }
        return true;

我想知道是否有一种紧凑的方法可以一次迭代到列表?

【问题讨论】:

标签: c# .net algorithm linq


【解决方案1】:

当然只使用Enumerable.ZipEnumerable.All

return theseParams.Count == otherParams.Count
    && theseParams.Zip(otherParams, (t,o) => new {These = t, Other =o})
    .All(x => x.These.Name == x.Other.Name);

【讨论】:

  • 重要说明,这不处理if(theseParams.Count != otherParams.Count) 检查,那部分仍然需要在代码中。 Zip 的行为类似于 for(int i = 0; i &lt; theseParams.Count &amp;&amp; i &lt; otherParams.Count; ++i)
  • @ScottChamberlain 错过了,现在修复了。
  • 虽然问题是重复的,但这个答案值得赞:)
猜你喜欢
  • 2014-11-03
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
相关资源
最近更新 更多