Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a C# dictionary and return a specific set of values

I have a dictionary in my C# program that contains a list of Key + Values.

The values are itemid, Month, Year, Count

I would like to query the dictionary by comparing a set of values (itemid, Month, Year) and return true or false if a the specific itemid + Month + Year exist.

So if all 3 values (itemid + Month + Year) exist return true else return false.

I tried something like this

(if (myd.Select(d => d.Value.itemid == item.itemid && d.Value.Month == DateRange.Month  && d.Value.Year == DateRange.Year).ToString() != "")

The above didn't work.

like image 670
Milligran Avatar asked Dec 05 '25 11:12

Milligran


2 Answers

You seem to misunderstand the usage of the Select() method. Select creates a "projection"; given an input collection (enumerable) of elements, it produces an output enumerable that is equal in cardinality, but is composed of elements that are each the result of a transformation of the corresponding element of the input.

What you need is either a Where() method (which returns a list, lesser or equal in cardinality to the input, of the elements from the input for which a boolean condition is true), or an Any() method (which returns a single "true" or "false" if any of the elements in the input meet the condition):

if(myd.Where(d => d.Value.itemid == item.itemid 
                && d.Value.Month == DateRange.Month 
                && d.Value.Year == DateRange.Year).Count() >= 1)
   ...

//produces the equivalent result but generally performs faster
if(myd.Any(d => d.Value.itemid == item.itemid 
                && d.Value.Month == DateRange.Month 
                && d.Value.Year == DateRange.Year))
   ...
like image 175
KeithS Avatar answered Dec 06 '25 23:12

KeithS


If like linq-Syntax, this checks if at least one item that satisfies all three condition exists:

if((from d in myd
where d.Value.itemid == item.itemid
&& d.Value.Month == DateRange.Month
&& d.Value.Year == DateRange.Year).FirstOrDefault() != null)
like image 42
Vertigo Avatar answered Dec 07 '25 01:12

Vertigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!