yomisimie yomisimie - 7 days ago 6
C# Question

C# how to search in Dictionary key by array of tags

I am learning c# and I am trying something simple: inputing some tags separated by comma the code to return a message. The idea is that the code should filter by all the tags that I am splitting into an array.

Defining the variables:

Dictionary<string[], string> messages = new Dictionary<string[], string>();
messages.Add(new string[] { "greeting", "hello", "hei", "hi" }, "Hello!");
messages.Add(new string[] { "greeting", "bye", "buh-bye", "sayonara" }, "Bye!");


Getting the tag:

string[] tags;
tags.Add("greeting");
tags.Add("hello");


The list and iterating:

List<string> lista = new List<string>();
foreach(string tag in e.GetArg("Tag").Split(','))
{
foreach (KeyValuePair<string[], string> entry in gifs)
{
if (entry.Key.Contains(tag))
{
lista.Add(entry.Value);
}
}
}


The problem with this is that it adds every met item for each tag in the list, even the bye item. Can I filter this with an array of tags? Or I need to pass it more times, each time getting the desired one(s)?

Answer

Search Dictionary by key array

        Dictionary<string[], string> messages = new Dictionary<string[], string>();
        messages.Add(new string[] { "greeting", "hello", "hei", "hi" }, "Hello!");
        messages.Add(new string[] { "greeting", "bye", "buh-bye", "sayonara" }, "Bye!");

        // add tags
        string[] tags = new string[2];
        tags[0] = "greeting";
        tags[1] = "buh-bye";

        List<string> lista = new List<string>(); // list to store the results

        // loop true the keys from every row
        // loop true the keys of the current row
        // check if tags contains key 
        // ckeck if lista already contains the key that was recognized(no duplicates in list)

        foreach (var value in messages.Keys)
            foreach (var value1 in value)
                if (tags.Contains(value1))
                    if(!lista.Contains(messages[value]))
                        lista.Add(messages[value]);

Output

      ==========
      lista Count = 2
      1: Hello
      2: Bye!
Comments