Pranab
Pranab

Reputation: 392

Merge Two or more list according to order

I have two Lists

List<string> Name = new List<string>();
List<string> Address = new List<string>();

Both the lists having 30 data. I want to merge both the lists to get a complete Information lists like

List<string, string> CompleteInformation = new List<string, string>();

Also if I want to merge more than two list in one how it can be done.

Upvotes: 4

Views: 117

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You're looking for Zip method:

var CompleteInformation = Name.Zip(Address, (n, a) => new { Address = a, Name = n }).ToList();

Gives you list of anonymous type instances, with two properties: Address i Name.

Update

You can call Zip more then once:

var CompleteInformation
    = Name.Zip(Address, (n, a) => new { Address = a, Name = n })
          .Zip(AnotherList, (x, s) => new { x.Address, x.Name, Another = s })
          .ToList();

Upvotes: 9

B.K.
B.K.

Reputation: 10152

There's also a dictionary method of something like this:

var people = Name.Zip(Address, (n, a) => new { n, a })
             .ToDictionary(x => x.n, x => x.a);

You can then access the keys and values. Easy to search for information.

Upvotes: 1

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9201

You can use a Tuple to store the information, and Zip method to take the info from both lists, like this

List<Tuple<string, string>> bothLists = Name.Zip(Address, (n, a) => new Tuple<string, string>(n, a)).ToList();

But the best way in my opinion would be to create a class related to your domain :

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
}

And then

List<Person> bothLists = Name.Zip(Address, (n, a) => new Person{Address = a, Name = n}).ToList();

However, if you have multiple lists you need to nest multiple Zips, and that's not pretty. If you are sure all lists have the same number of elements, just iterate over them.

In LINQ :

List<Person> multipleLists = Name.Select((t, i) => new Person
    {
        Name = t, Address = Address[i], ZipCode = ZipCode[i]
    }).ToList();

Without LINQ (seriously, there's nothing wrong with a for loop)

List<Person> multipleLists = new List<Person>();
for (int i = 0; i < Name.Count; i++)
{
    multipleLists.Add(new Person
        {
            Name = Name[i],
            Address = Address[i],
            ZipCode = ZipCode[i]
        });
}

You can also use a Tuple<string, string, string, [...]> if you want to stay away from classes.

Upvotes: 6

Related Questions