Combine two or more lists as ordered

I have two lists

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

Both lists contain 30 data. I want to combine both lists to get complete information lists, e.g.

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

Also, if I want to combine more than two lists into one, how can this be done.

+4
source share
3 answers

You are looking for a method Zip:

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

It gives you a list of instances of an anonymous type with two properties: Addressi Name.

Update

You can call Zipmore than 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();
+9
source

You can use Tupleto store information and Zipto get information from both lists, for example

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

, , , :

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

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

, , Zips, . , , .

LINQ:

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

LINQ (, for)

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

Tuple<string, string, string, [...]>, .

+6

There is also a dictionary, for example:

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

Then you can access the keys and values. Easy to search for information.

+1
source

Source: https://habr.com/ru/post/1528248/


All Articles