Vishal
Vishal

Reputation: 12379

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

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 ?

Upvotes: 1

Views: 3001

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1504052

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

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

IDictionary<DateTime, int> kamptslist = GetListofdates()
    .Zip(
        GetListofints(), 
        (date, value) => new { date, value })
    .ToDictionary(x => x.date, x => x.value);

Upvotes: 0

jason
jason

Reputation: 241789

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

Upvotes: 6

Related Questions