Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a value from within a List of Dictionary objects

Tags:

c#

linq

I have what can potentially be a very large list of Dictionary objects that I will need to find a particular value from a key. I can certainly do something like

foreach(Dictionary<long, string> t in Foo)
{
    if (t.TryGetValue(key, out name))
        break;
}

and this will happily iterate through Foo until it finds the key or the foreach ends.

To speed this up, I'd prefer to use a small amount of LINQ. If this was a normal list, I'd be ok, but as this is a List of Dictionary objects, I'm not too sure how it's done.

Help or advice appreciated.

like image 566
Nodoid Avatar asked May 07 '13 17:05

Nodoid


1 Answers

I think you have written the most efficient version of what you want to do. Since Linq doesn't play nicely with output parameters, it will take slightly longer. But here is how you would do it:

var dict = Foo.FirstOrDefault(d => d.ContainsKey(key));
if (dict != null) { dict.TryGetValue(key, out name); }
like image 71
Ben Reich Avatar answered Sep 29 '22 05:09

Ben Reich