c# - Linq to objects: if number is in dictionary, return number, else return 0 -
i have dictionary<int int>
. when check keys of dictionary number , in it, want return number, else want linq query return 0.
something following, except working
var t = (from result in results result.key == 3 select result.key != null ? result.value : 0).first();
because problem when there no number in list, sequence contains no element, can't check null or count.
just use trygetvalue
.
int i; results.trygetvalue(3, out i);
if finds it, i
set value. if not, i
default, 0 int.
if want value besides default, can this:
int i; if (!results.trygetvalue(3, out i)) { = 5; // or whatever other value want; }
and if you, me, hate out
parameter style, can create extension method
public static class idictionaryextensions { public static tvalue getvalueordefault<tkey, tvalue>(this idictionary<tkey, tvalue> dictionary, tkey key) { t i; dictionary.trygetvalue(key, out i); return i; } }
and can call:
int = dictionary.getvalueordefault(3);
and if want fancier can create oveload of extension:
public static tvalue getvalueordefault<tkey, tvalue>(this idictionary<tkey, tvalue> dictionary, tkey key, tvalue defaultvalue) { t i; return dictionary.trygetvalue(key, out i) ? : defaultvalue; }
which can called
int = dictionary.getvalueordefault(3, 5);
Comments
Post a Comment