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
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])
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With