user1108948
user1108948

Reputation:

Use ToDictionary to create a dictionary

I have two string lists which have same size. I want to create a dictionary, the key is from listA, the value is from listB.

What is the fast way?

I used the code:

        List<string> ListA;
        List<string> ListB;
        Dictionary<string,string> dict = new Dictionary<string,string>();
        for(int i=0;i<ListA.Count;i++)
        {
              dict[key] = listA[i];
              dict[value]= listB[i];
        }

I don't like this way, can I use ToDictionary method?

Upvotes: 6

Views: 465

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

Starting with .NET 4.0, you can do it using LINQ's Zip method, like this:

var res = ListA.Zip(ListB, (a,b) => new {a, b})
               .ToDictionary(p=>p.a, p=>p.b);

[Zip] method merges each element of the first sequence with an element that has the same index in the second sequence.

Upvotes: 14

ken2k
ken2k

Reputation: 49013

I wouldn't change your version.

The following piece of code is more readable than LINQ stuff in your case, IMHO.

var ListA = new List<string>();
var ListB = new List<string>();
var dict = new Dictionary<string, string>();

for (int i = 0; i < ListA.Count; i++)
{
    dict.Add(ListA[i], ListB[i]);
}

Upvotes: 2

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

I would not bother (if it is possible) as your version is readable, easy to debug and quicker than any other LINQ solutions (especially if you are working with big list).

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460238

You could create an anonymous type with the index which you can use to get the B at this index.

Dictionary<string, string> dict = ListA
    .Select((a, i) => new { A = a, Index = i })
    .ToDictionary(x => x.A, x => ListB.ElementAtOrDefault(x.Index));

Note that the value would be null in case ListB is smaller than ListA.

Upvotes: 4

Related Questions