Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi Guys,

I have two lists and in new list i want to merge these two as two columns, in c#.

What I have tried:

i have tried using contact but it is add list in one column only.

plz help me guys.

Thanks
Posted
Updated 31-Aug-16 14:04pm
Comments
Tomas Takac 30-Aug-16 4:27am    
Not clear, you want a Cartesian product of the two lists? Or you want to join them by some key?
Patrice T 30-Aug-16 5:29am    
What have you dome ?
Show code and explain problem.

That's complicated, because it depends on what is in the two lists. If they share a common value, you can JOIN them fairly easily, but I suspect from your wish to combine them as two columns in a new list that they don't.
In that case, it's a bit complicated, but:
C#
List<string> ls = new List<string>();
ls.Add("S1");
ls.Add("S2");
ls.Add("S3");
ls.Add("S4");
List<int> li = new List<int>();
li.Add(1);
li.Add(2);
li.Add(3);
li.Add(4);
var newList = ls.Join(li, s => ls.IndexOf(s), i => li.IndexOf(i), (s, i) => new { sv = s, iv = i }).ToList();
foreach (var x in newList)
    {
    Console.WriteLine("{0}, {1}", x.sv, x.iv);
    }

Will give you the two columns you seem to want:
S1, 1
S2, 2
S3, 3
S4, 4
 
Share this answer
 
Comments
Maciej Los 30-Aug-16 4:44am    
5ed!
Member 13946703 3-Oct-18 9:01am    
When i used this code, the output was the same row repeated foreach item in newList (ex: S1,1
S1,1
S1,1
S1,1)
How to i fix this?
OriginalGriff 3-Oct-18 9:59am    
I wrote that 2 years ago, when your code and data was not available to me.
How do you expect me yo have any idea what you actually did or what you did it to?
It looks like you could just use Linq's .Zip():
C#
// "borrowing" from OriginalGriff's code ;-)
List<string> ls = new List<string>();
ls.Add("S1");
ls.Add("S2");
ls.Add("S3");
ls.Add("S4");
List<int> li = new List<int>();
li.Add(1);
li.Add(2);
li.Add(3);
li.Add(4);
var newList = ls.Zip(li, (s, i) => new { sv = s, iv = i }).ToList();
foreach (var x in newList)
{
  Console.WriteLine("{0}, {1}", x.sv, x.iv);
}

If the lists are different lengths, .Zip() will stop when either runs out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900