3

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.

1
  • Try to loop thru the dictionary and compare the values adding them to another dictionary
    – COLD TOLD
    Feb 21, 2012 at 21:39

5 Answers 5

3

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))
   ...
5
  • Combination of where and count is not efficient, Also is not good. Feb 21, 2012 at 21:48
  • ... which I stated in the comment in the code. Whether he uses Where or Any depends on exactly what result he needs; Where()'s result is an enumerable that can be further processed, while Any() produces a concrete result. I gave him both so he could see that both methods take the lambda he'd tried to use with Select and produce the correct answer.
    – KeithS
    Feb 21, 2012 at 21:51
  • The usage is obvious, it's within if condition, Also combination of where and count is not good anyway (except in linq2sql, still is redundant there) you can write: myList.Count(x=>f(x)), there is no need to use where (causing to one more iteration, per check totally 2n instead of n), Also as I said at first, it's not good (readability, efficiency, logically, technically, anything comes in mind). Feb 21, 2012 at 21:55
  • Thanks. I tried that but I keep getting false when I use myd.Any. I can see from debugging my application that the item definetly exsist in the dictionary.
    – Milligran
    Feb 21, 2012 at 22:08
  • I think I have found the reason why I am getting all false. My dictionary seem to be adding spaces to the values. Example month = "4 " year = "2011 "
    – Milligran
    Feb 21, 2012 at 22:19
1

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)
1
  • 1
    You can simply write: myList.FirstOrDefault(x=>f(x)), in fact you can use where conditional function in FirstOrDefault. Feb 21, 2012 at 21:50
0

You'll need to create a 2nd dictionary if you want to do lookups with another key (in this case itemid,month,year, probably placed into a Tuple), and you'll need to maintain them both whenever you add/remove from either.

0

use Where to filter (I'm assuming the condition in your code is defined correctly... you haven't given us enough info to evaluate that)

var filteredDictionary = myd.Where(d => d.Value.itemid == item.itemid && d.Value.Month == DateRange.Month  && d.Value.Year == DateRange.Year)

use Select to transform from a KeyValuePair to just a value

var filteredValues = filteredDictionary.Select(x=>x.Value)

use Any to return a bool of whether or not an item exists

bool matchExists = myd.Any(d => d.Value.itemid == item.itemid && d.Value.Month == DateRange.Month  && d.Value.Year == DateRange.Year)

Any is going to be most efficient for the problem you describe because it will stop evaluating items in the dictionary and return True as soon as a match is found

0

If you are working with .NET 4.0 you can use Tuples as keys.

var dict = new Dictionary<Tuple<int,int,int>,MyValueType>();

You can then test if a value exists with

var key = new Tuple<int,int,int>(item.itemid, DateRange.Month, DateRange.Year);
if(dict.ContainsKey(key)) {
   ...
}

Or you can test

if(dict.ContainsValue(referenceValue)) {
    ...
}

You will have to pass it a reference value containing what you are looking for. Make sure that your value type implements EqualityComparer<T>.

The first method will be much faster, since the dictionary is accessed by the key. If you are not accessing the dictionary by the key, you could use a List<T> as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.