Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using a LINQ Where clause on a Dictionary, how can I return a dictionary of the same type?

I'm currently using the following code to achieve this, but is seems there should be something better... suggestions? It just seems to me there should be a way to skip the foreach...

Dictionary<string,string> getValidIds(Dictionary<string,string> SalesPersons,List<string> ids)
{
    Dictionary<string,string> o = new Dictionary<string,string>();
    var ie = SalesPersons.Where<KeyValuePair<string, string>>(t => ids.Contains(t.Key));
    foreach (var i in ie)
    {
        o.Add(i.Key, i.Value);
    }
    return o;
}
like image 964
Loki Avatar asked May 22 '09 09:05

Loki


People also ask

How do you retrieve a value for a key in a dictionary C#?

The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.

Can we store duplicate values in dictionary C#?

Its not possible to add duplicate items to a Dictionary - an alternative is to use the Lookup class.

What is dictionary type in C#?

Dictionary is a collection of keys and values in C#. Dictionary is included in the System. Collection. Generics namespace.


1 Answers

Pretty sure you could just call ToDictionary on the result of the Where call:

Dictionary<string, string> GetValidIds(Dictionary<string, string> salesPersons,
    IList<string> ids)
{
    return salesPersons
        .Where(p => ids.Contains(p.Key))
        .ToDictionary(p => p.Key, p => p.Value);
}
like image 53
Matt Hamilton Avatar answered Sep 20 '22 10:09

Matt Hamilton