I've got a problem searching a Dictionary looking like this.
Dictionary<string, string[]> dic = new Dictionary<string, string[]>(){
{"a", new string[](){"a_val","2"}},
{"b", new string[](){"b_val","1"}},
{"b", new string[](){"b_val","0"}}
};
I need to return a List of the Keys where the value of the stingArray[1] element is bigger than "1" like:
List<string> list = new List<string>{
"a"
};
Because I'm not really good at using LINQ, my current solution is iterating over the Dictionary and adding the keys to a new list. But that method looks ugly and I'm trying to find another solution to the problem.
Filter a Dictionary by values in Python using filter() filter() function iterates above all the elements in passed dict and filter elements based on condition passed as callback.
It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.
Without any error handling:
var list = dic.Where(x => int.Parse(x.Value[1]) > 1)
.Select(x => x.Key)
.ToList();
With the Where
statement the entries where Value[1]
is greater 1 will be filtered and with the Select
statement the key from this entries will be selected. At least the collection will be converted in a List
with the ToList
method.
For further information have a look at 101 LINQ Samples in C#
Try this(You're dictionary definition has some compiling errors and I made some guess):
static void Main(string[] args)
{
var dic = new Dictionary<string, string[]>(){
{"a", new string[]{"a_val","2"}},
{"b", new string[]{ "b_val","1"}},
{"c", new string[]{ "b_val","0"}}};
string[] expected = dic
.Where(kv => Convert.ToInt32(kv.Value[1]) > 1)
.Select(kv => kv.Key).ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With