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;
}
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.
Its not possible to add duplicate items to a Dictionary - an alternative is to use the Lookup class.
Dictionary is a collection of keys and values in C#. Dictionary is included in the System. Collection. Generics namespace.
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);
}
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