Nejchy
Nejchy

Reputation: 666

Query SortedList<Object1,Object2> with Linq

I'm a complete begginer with Linq. And I woild like to know, if it is possible to make a query where for a given Class1.Code I get matching Class2.Value.

class Class1()
{
    public string Code;
    ...
}

class Class2()
{
    public double Value;
    ...
}

SortedList<Class1, Class2>

Thank you for your help.

Upvotes: 1

Views: 2242

Answers (3)

Dan Cristoloveanu
Dan Cristoloveanu

Reputation: 2058

SortedList < Class1, Class2 > x;

One way to write it:

(from pair in x where pair.Key.Code == matchingValue select pair.Value.Value)

where matchingValue is the Class1.Code you want to search for.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422026

list.First(x => x.Key.Code == codeToSearch).Value

However, this is not efficient (O(n)). I guess this is not the correct way to approach the problem. If you are searching by Code most of the time, you should probably make it a SortedList<string, Class2> and store Code as the key.

Upvotes: 2

LorenVS
LorenVS

Reputation: 12867

double value = (from kv in SortedList
                where kv.Key.Code = "CodeI'mLookingFor"
                select kv.Value.Value).FirstOrDefault();

Upvotes: 1

Related Questions