How to add items using Lists to Dictionary without looping through it?

2.9k Views Asked by At

I have this Dictionary-

IDictionary<DateTime, int> kamptslist = new Dictionary<DateTime, int>();
List<int> listints= GetListofints(); //for values
List<int> listdates= GetListofdates();// for keys

Can I somehow assign the lists directly to the Dictionary instead of actually doing a foreach and adding one item at a time ?

3

There are 3 best solutions below

1
On

You can do this easily with .NET 4:

var dictionary = listints.Zip(listdates, (value, key) => new { value, key })
                         .ToDictionary(x => x.key, x => x.value);

Without .NET 4 it's a bit harder, although you could always use a grotty hack:

var dictionary = Enumerable.Range(0, listints.Count)
                           .ToDictionary(i => listdates[i], i => listints[i]);

EDIT: As per comment, this works fine with an explicitly typed variable to:

IDictionary<DateTime, int> kamptslist = 
     listints.Zip(listdates, (value, key) => new { value, key })
             .ToDictionary(x => x.key, x => x.value);
4
On

Use Enumerable.Zip to zip the two sequences together, and then use Enumerable.ToDictionary:

var kamptslist = listdates.Zip(listints, (d, n) => Tuple.Create(d, n))
                          .ToDictionary(x => x.Item1, x => x.Item2);
0
On
IDictionary<DateTime, int> kamptslist = GetListofdates()
    .Zip(
        GetListofints(), 
        (date, value) => new { date, value })
    .ToDictionary(x => x.date, x => x.value);