0
public IDictionary<IContextType, IDictionary<string, string>> MasterScopeVariablesTable
                       = new Dictionary<IContextType, IDictionary<string, string>>();

I have a keyed dictionary of dictionaries. I would like to use LINQ to query the LAST entry from any dictionary that contains the "key" with name "State". The dictionaries have some of the same keys with different values.

Similar to this link Query a Dictionary of Dictionaries?

But this can be done in a single call without a foreach loop, does anyone know how?

Community
  • 1
  • 1
Craig Trombly
  • 464
  • 2
  • 9
  • 6
    explain `LAST` here? Order in `IDictionary` is not guaranteed, consider `IOrderedDictionary` – Ilya Ivanov Mar 06 '15 at 16:55
  • They are in order by when they were created. I am positive of this because I am using an IDispose method to drop the last key dictionary from the master. – Craig Trombly Mar 06 '15 at 17:04
  • 3
    think again http://stackoverflow.com/questions/4007782/the-order-of-elements-in-dictionary, the elements could have been in that order in your testing. Do you want to write code that works in your testing or, all the time? – Jodrell Mar 06 '15 at 17:06
  • This works, but I do not want to use the [ContextType] as an index and just want any one of the dictionaries with a keyname of "State" – Craig Trombly Mar 06 '15 at 17:10
  • var ret = (from ctx in MasterScopeVariablesTable[ContextType] where ctx.Key == key select ctx.Value).Last(); – Craig Trombly Mar 06 '15 at 17:10
  • 2
    @CraigTrombly The last item of an unordered set is effectively getting a random item from that set. You have no idea which item you'll actually get. If you want to get one item at random, rather than a specific item, then go ahead. If the items that you have are logically ordered, and that order matters, then don't use an unordered collection. – Servy Mar 06 '15 at 17:13
  • I don't get you guys. It's a DICTIONARY, when I query it by KEY it comes back. The use of LAST was simply to all LINQ to (CAST) the Keyvaluepair into a single string in the call. WHAT NO ONE has answered is my PRIMARY question posted – Craig Trombly Mar 06 '15 at 17:28
  • @CraigTrombly In that case, why are you asking for the last entry rather than the first one? That apparently matters to you. Nobody can answer your primary question because the entire premise is flawed. – JLRishe Mar 06 '15 at 18:43

1 Answers1

-1
var res = (from ctx in MasterScopeVariablesTable from ctxDict in ctx.Value where ctxDict.Key == key select ctxDict.Value).Last();

This is the correct answer for those who would like to see it. Mainly because I could not find a single answer to this exact question anywhere else.

Craig Trombly
  • 464
  • 2
  • 9