Map two lists into a dictionary in C#
With .NET 4.0 (or the 3.5 version of System.Interactive from Rx), you can use Zip()
:
var dic = keys.Zip(values, (k, v) => new { k, v })
.ToDictionary(x => x.k, x => x.v);
Or based on your idea, LINQ includes an overload of Select()
that provides the index. Combined with the fact that values
supports access by index, one could do the following:
var dic = keys.Select((k, i) => new { k, v = values[i] })
.ToDictionary(x => x.k, x => x.v);
(If values
is kept as List<string>
, that is...)
I like this approach:
var dict =
Enumerable.Range(0, keys.Length).ToDictionary(i => keys[i], i => values[i]);
If you use MoreLINQ, you can also utilize it's ToDictionary extension method on previously created KeyValuePair
s:
var dict = Enumerable
.Zip(keys, values, (key, value) => KeyValuePair.Create(key, value))
.ToDictionary();
It also should be noted that using Zip
extension method is safe against input collections of different lengths.