-2

I have a string List that contains some numbers . I have some string in mybuylist that matches in Dictionary list. But this if condition always returns False. Ok mybuylist like [34,45,58] and mcollection(key,value) like this {[565,5]},{[34,1]},{[78,9]}....

public static Dictionary<string, int> mcollection = new Dictionary<string, int>();
public static List<string> mybuylist = new List<string>();

foreach (string entry in mybuylist) {

 if (mcollection.ContainsKey(entry))
    {
     //dosomething                     

    }

}

Hope someone help me about this

Erdem Alkan
  • 157
  • 1
  • 2
  • 7

1 Answers1

0

It might be the the problem of case-sensitive comparison or Keys are not matching. All Dictionaries are case-sensitive by default. A and a are different. Verify whether the values in mybuylist and mcollection are same or not.

Declare mcollection like below.

public static Dictionary<string, int> mcollection = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

This will ignorecase and A & a are same.

See this.

EDIT 1:

class Program
{
    public static Dictionary<string, int> mcollection = new Dictionary<string, int>() { { "565", 5 }, { "34", 1 }, { "78", 9 } };
    public static List<string> mybuylist = new List<string>() { "34", "45", "58" };

    static void Main(string[] args)
    {
        foreach (string entry in mybuylist)
        {
            if (mcollection.ContainsKey(entry))
            {
                Console.WriteLine(entry);
                //dosomething                     
            }
        }
    }
}

O/P: 34

EDIT 2: Use below code to remove the spaces

mybuylist = mybuylist.ConvertAll(s => s.Trim());
Community
  • 1
  • 1
Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62