Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine two lists to a List<KeyValuePair<>>?

Tags:

c#

lambda

linq

There are two lists:

List<string> files;
List<Filter> filters;

I want the result to be like:

List<KeyValuePair<string, Filter>> fileFilterMap;

I tried several stuff (lambda expressions, linq) but failed. I really do not want the

for(int i = 0; i< files.count; i++)

method.

like image 433
Odys Avatar asked Dec 12 '11 15:12

Odys


2 Answers

You can use:

List<KeyValuePair<string, Filter>> fileFilterMap =
  Enumerable.Range(0, files.Count)
  .Select(i => new KeyValuePair<string, Filter>(files[i], filters[i]))
  .ToList();

Or:

List<KeyValuePair<string, Filter>> fileFilterMap =
  Enumerable.Zip(
    files,
    filters,
    (file, filter) => new KeyValuePair<string, Filter>(file, filter)
  )
  .ToList();
like image 154
Guffa Avatar answered Nov 13 '22 12:11

Guffa


Have a look at Enumerable.Zip.

var fileFilterMap = Enumerable.Zip(files, filters, (file, filter) => new KeyValuePair(file, filter));
like image 26
Stefan Paul Noack Avatar answered Nov 13 '22 10:11

Stefan Paul Noack