Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use linq expression to filter a dictionary with a list of keys

Tags:

c#

linq

I have a dictionary containing all users with their corresponding age.

Dictionary<string,int> AllUsers;

I have a list of specific users.

List<String> Users;

I would like to filter the first dictionary AllUsers with only the users who have their name in the SpecificUsers list.

I have done something manually with loops but I would like to use linq expression but I am not very familiar with them.

Thanks in advance for your help

like image 519
user2443476 Avatar asked Sep 04 '15 11:09

user2443476


2 Answers

You could filter Users:

Users.Where(i => AllUsers.ContainsKey(i)).Select(i => new { User = i, Age = AllUsers[i] });

The major benefit of this is that you're using the indexed AllUsers to do the filtering, so your total computational complexity only depends on the amount of users in Users (Dictionary.Contains is O(1)) - the naïve approaches tend to be Users * AllUsers.

If you want a dictionary on output, it's as simple as replacing the .Select(...) above with

.ToDictionary(i => i, i => AllUsers[i])
like image 170
Luaan Avatar answered Oct 16 '22 05:10

Luaan


It might work

var newdict = AllUsers.Where(x => Users.Contains(x.Key))
                                        .ToDictionary(val => val.Key, val => val.Value);

it will create new dictionary (cause linq is for querying not updating) with all the users from dictionary that are on the Users list. You need to use ToDictionary to actualy make it dictionary.

EDIT: As @Rawling said it would be more performant to filter on Dictionary rather than on list. Solution to achieve that is present in @Luaan answer (I won't copy it as some do)

like image 43
Kamil Budziewski Avatar answered Oct 16 '22 03:10

Kamil Budziewski