【发布时间】: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?
【问题讨论】:
我有两个列表,列表 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?
【问题讨论】:
试试这个
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 框架中。
【讨论】: