tags:

views:

34

answers:

2

i have two list , List A,List B both have same no of values.i like to pass these values as arguments and selecting returning value .here code

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

how can i do this using linq.Is it possible to do in .net 3.5

+2  A: 

Are you using .NET 4? If so, the Zip method is what you want:

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

Or using a method group conversion:

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

If you're not using .NET 4, MoreLINQ has a simple implementation of Zip too.

Jon Skeet
No i am using .net framework 3.5
ratty
A: 

Try this

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])));

Suppose if I modify your existing code as under

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;
}

I will get the output as 12,24,36,48.

Running the one I provided will fetch the same answer.

Hope this helps.

and it is in 3.5 framework.

priyanka.sarkar_2