Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search dictionary values and return List of keys meeting conditions

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.

like image 867
McNade Avatar asked Jul 05 '17 08:07

McNade


People also ask

How do you filter a dictionary based on values?

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.

Can dictionary have list as values?

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.


2 Answers

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#

like image 168
Mighty Badaboom Avatar answered Oct 12 '22 22:10

Mighty Badaboom


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();
    }
like image 22
Lei Yang Avatar answered Oct 12 '22 22:10

Lei Yang