-9

I have collection of dictionaries.

public class Bills
    {
        public Dictionary<string, string> billList { get; set; }
    }

From the list of instances of this class 'Bill' List<Bills> allBills, how would I get all the records where key equals 'User' and name equals 'Nick'

Bijoy K Jose
  • 1,342
  • 3
  • 15
  • 26

2 Answers2

4

None of the other answers leverage the lookup-speed of the dictionary:

var matches = allBills
        .Where(dict => dict.billList.ContainsKey("User"))
        .Where(dict => dict.billList["User"] == "Nick");
Dave Bish
  • 19,263
  • 7
  • 46
  • 63
  • Better than mine, +1 :) – Mathew Thompson Mar 27 '13 at 10:57
  • 1
    why not `.Where(dict => { string name; return dict.billList.TryGetValue("User", out name) && name == "Nick"; });` Only doing the dictionary lookup once then – Andras Zoltan Mar 27 '13 at 10:58
  • Yeah - could do that - pretty-sure behind the scenes 'trygetvalue' that it's doing the exact same thing - and I think this is more readable. – Dave Bish Mar 27 '13 at 11:02
  • @AndrasZoltan - I'm wrong. TryGetValue is faster: http://stackoverflow.com/questions/9382681/what-is-more-efficient-dictionary-trygetvalue-or-containskeyitem – Dave Bish Mar 27 '13 at 11:04
1
string key = "User";
string name = "Bill";

if (billList.ContainsKey(key))
{
    string result = billList[key];
    if (result == name)
        return result;
}
return null; // key and names did not match

A Dictionary will never have more than one occurence of the same key, so I wonder if you shouldn't be using a Dictionary<string, Bill> instead, in which case the code would look more like this:

return billList.Where(kvPair => kvPair.Value.Key == key &&
                                kvPair.Value.Name == name).Select(kvPair => kvPair.Value);

This code assumes that the Bill class contains a Key and a Name field.

Nolonar
  • 5,962
  • 3
  • 36
  • 55