【问题标题】:how retrieve the value from more than one list at a time using linQ?如何使用 linQ 一次从多个列表中检索值?
【发布时间】:2010-10-19 06:15:10
【问题描述】:

我有两个列表,列表 A,列表 B 都有相同的值。我喜欢将这些值作为参数传递并选择返回值。这里代码

for(int i=0;i<A.count;i++)
{
list<int> temp=new list<int>();
temp.add(methodA(A[i],B[i]);
}

我如何使用 linq 来做到这一点。我是如何做到的 .net framework 3.5?

【问题讨论】:

    标签: c# .net linq .net-3.5


    【解决方案1】:

    您使用的是 .NET 4 吗?如果是这样,Zip 方法就是你想要的:

    List<int> temp = A.Zip(B, (a, b) => SomeMethod(a, b)).ToList();
    

    或者使用方法组转换:

    List<int> temp = A.Zip(B, SomeMethod).ToList();
    

    如果您不使用 .NET 4,MoreLINQ 也有一个简单的 Zip 实现。

    【讨论】:

      【解决方案2】:

      试试这个

      List<int> A = new List<int>() { 1, 2, 3, 4 };
      List<int> B = new List<int>() { 11, 22, 33, 44 };
      List<int> temp = new List<int>(); 
      
      Enumerable.Range(0, A.Count)
      .ToList()
      .ForEach(i => temp.Add(methodA(A[i], B[i])));
      

      假设如果我修改你现有的代码如下

      List<int> A = new List<int>(){1,2,3,4};
      List<int> B = new List<int>(){11,22,33,44};
      List<int> temp = new List<int>(); 
      for(int i=0;i<A.Count;i++) temp.Add(methodA(A[i],B[i])); 
      
      //Method for some operation
      private int methodA(int val1, int val2)
      {
                  return val1 + val2;
      }
      

      我会得到输出为 12,24,36,48。

      运行我提供的那个会得到相同的答案。

      希望这会有所帮助。

      它在 3.5 框架中。

      【讨论】:

        猜你喜欢
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        • 2013-02-06
        • 1970-01-01
        相关资源
        最近更新 更多