views:

297

answers:

4

Okay, this could be rather in depth but I'll try to ask a clear question: how can I find the first value in a Dictionary<int, MyTableClass> where MyTableClass inherits Field<F1, F2, F3>? I'd prefer a Property or Property/Method combination that returns the first value in the Dictionary where F1 = MyEnum.value.

What I don't want to do is a foreach. Performance-wise, this is really not a preferred method. Any help would be gratefully appreciated.

Regards, David

A: 

You could use the .First() extension method.

maxpower47
+3  A: 

No matter how you dress it up here you are going to essentially have to do a foreach over the values in the Dictionary. A Dictionary<TKey,TValue> provides close to O(1) access for a full key to a given value. It is not designed to provide efficient access to a partial key. In order to get that you would need to keep a second Dictionary instance making the appropriate mapping.

JaredPar
+2  A: 

The shortest way to find a value matching some criteria (I couldn't quite understand what you want specifically - first F1 is a generic type parameter, and then you use == to compare it as if it was a value...) is to do this:

dictionary.Values.First(x => ...);

where ... will be a boolean expression on x. However, this will not be any faster than foreach (I explained why in a separate comment to your question).

Pavel Minaev
+2  A: 

The dictionary doesn't maintain any specific order between element, so there isn't really any element that can be the first one unless you specify some ordering.

You can get the first item that the dictionary happens to find like this:

MyTableClass one = dict.Where(pair => pair.Value.F1 == MyEnum.value).First();

This will just loop through the items until it finds a match, so you are just using the dictionary as a list. If you want any performance, you should have a dictionary where the value from F1 is the key.

Guffa
Thanks everyone for your answers. I was pretty much assured that foreach would be the only way to do what I wanted - but just wanted to see if anyone had ideas I hadn't thought of... :)
dboarman