tags:

views:

83

answers:

2

Hi, Lets look at the following structure first (I have tried to simplify it to just show what kind of query I want)

class NameAddress
  {    
      public string Name { get; set; }
      public string Address { get; set; }
      public NameAddress(string sName, string sAddress) { Name = sName; Address = sAddress; }    
  }

  static void Main(string[] args)
  {
      Dictionary<int, Dictionary<string, NameAddress>> _dictionary = new Dictionary<int,Dictionary<string,NameAddress>>() 
          { 
            {/*int Key=*/1, /*Dictionary<str, NameAddress> value(1)=*/new Dictionary<string, NameAddress>() { {"First", new NameAddress("John Doe", "Mexico")}} },
            {/*int Key=*/2, /*Dictionary<str, NameAddress> value(2)=*/new Dictionary<string, NameAddress>() { {"Second", new NameAddress("Morris", "Washington")}, { "Third", new NameAddress("Keith", "New York")}} }
          };    
   }

I want to query the following data structure using a single linq query. Let's say I want to find the guy who lives in New York and HIS key as well. The integer keys (_dictionary Keys) are not that important but the string Key (in this case - "Third") is the one that I want to find out.

Is it possible to find that the string Key and the particular NameAddress in a single linq query? If yes, what is that query?

+2  A: 

This is not an efficient data structure for supporting this operation. If it is a common operation, you should consider a new design.

Check the culture requirements.

string address = "New York";
KeyValuePair<string, NameAddress> result =
    _dictionary.Values
               .SelectMany(value => value)
               .FirstOrDefault(pair => pair.Value.Address.Equals(address, StringComparison.CurrentCultureIgnoreCase));
280Z28
I agree, it's not efficient. I was trying to do some reverse lookup (for fun) and got stuck. Hence, asked here out of curiosity.
BrainCracker
+2  A: 

Note that this iterates over the dictionary (rather than using the index), but it works:

  var found = (from outer in _dictionary
               from inner in outer.Value
               where inner.Value.Address == "New York"
               select new {
                   OuterKey = outer.Key,
                   InnerKey = inner.Key,
                   NameAddress = inner.Value
               }).FirstOrDefault();
Marc Gravell
I was looking for something like this only. Didn't know how to do the nested query. Thanks
BrainCracker
I still think mine is cleaner lol ;)
280Z28