Reputation: 23
I have a dictionary which looks like this:
Dictionary<String, String> dictionary = new Dictionary<string, string>{
{ "dog", "DOG" },
{ "cat", "CAT" },
...continued
};
and I want to extract the Id value from a list that has a matching value like below:
List<Animal> records = new List<Animal>{
{ Id: "1", Name: "DOG" },
{ Id: "2", Name: "CAT" }
...continued
}
I need to output a dictionary that looks like this:
Dictionary<String, String> newDictionary = new Dictionary<string, string>
{ "dog": "1" },
{ "cat": "2 }
...continued
}
Is there a simple LINQ solution to this?
Upvotes: 0
Views: 99
Reputation: 6217
You can use JOIN
to get matching records from dictionary and list like this:
var query = from d in dictionary
join r in records
on d.Value equals r.Name
select new { Id=r.Id, Name=d.Key };
var newDictionary = query.ToDictionary(d => d.Name, d => d.Id);
Upvotes: 5