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.
In Python, there are a few different ways we can get the first key/value pair of a dictionary. The easiest way is to use the items() function, convert it to a list, and access the first element. If you only care about getting the first value of a dictionary, you can use the dictionary values() function.
Python lists are zero-indexed. Thus, the first element is at position 0, the second is at position 1, the third is at position 2, and so on.
You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.
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
...because you're not doing a lookup on dictionary key. Only key lookup is fast; for anything else, you have to do a linear scan (or maintain a second dictionary for a different key, which will be whatever you do lookups on). [copied from comment]
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.
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.
You could use the .First() extension method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With