简体   繁体   中英

List<double> for value of dictionary lookup specific item

I have a Dictionary with 5 different doubles in the list. I know the order of each item in the List. I am trying to find a one liner piece of code where I can lookup a specific value in my list given the key.

So something like:

double myDbl = myDict["key"][value[3]];

Is something like this possible, I cant find it anywhere. Thanks

As others have said, if this is a Dictionary<string, List<double>> you could just use

double value = myDict["key"][3];

However, this line:

I know the order of each item in the List.

makes me think that actually you should restructure your code. If you know that the first item always represents one piece of data (eg weight), the next always represents another (eg height) etc, then you should just create a new type with those properties. Using a List<double> for this will make the code much harder to maintain... it doesn't naturally reveal the information about what each value means.

Once you've changed it to, say, a Dictionary<string, Person> you can use:

double height = myDict["key"].Height;

which is significantly clearer.

Of course it's possible that you meant something else by the line I've quoted...

Assuming you have a dictionary defined as

Dictionary<string,List<double>>

And assuming the dictionary elements are initialized correctly you can do the following:

myDbl = myDict["key"][3];

It should probably be something like:

double myDbl = myDict["key"][3];

As you're looking for index 3 from the resulting list from the key

By understanding the order in which the operators are executed, you can see that myDict["key"] will return your value type, which here is assumed to be List<double> . From this return value, you then want to get the 4th object (0 based) so you use [3] at the end.

Given:

Dictionary<string, List<double>> l_dict = new Dictionary<string, List<double>>();
l_dict.Add( "key", new List<double>( new double[]{ 1, 2, 3, 4, 5 } );

Then:

List<double> l_valueCollection = l_dict["key"];
double l_value = l_valueCollection[3];

Or, more succinctly (the "one-liner" you wanted):

double l_value = l_dict["key"][3];

If your collection looks like this:

Dictionary<string,List<double>> myDictionary;

Then the following will work:

double myDouble = myDictionary["key"][3];

Create a method like this that returns your value, no matter what key you pass in.

    private double GetValue(Dictionary<string, double> dict, string key)
    {
        return (from pair in dict where pair.Key == key select pair.Value).FirstOrDefault();
    }

Remember that this is using LINQ and will only work with .Net Framework 3.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM