0

I have a Dictionary collection with integer array as a Key and Image as Value. I need to check whether if same key is already exists or not , before adding new int[].

I have tried below code, but the Dictionary.ContainsKey(int[]) method will always fails, even the same key is already exists.

Dictionary<int[], Image> temp = new Dictionary<int[], Image>();
int[] rowcol = new int[]{rowIndex,colIndex};
if (!temp.ContainsKey(rowcol))
{
    animatedImage = style.BackgroundImage;
    temp.Add(rowcol, animatedImage);
}

Please suggest me how to check the int[] key in Dictionary?

Thanks

Thomas
  • 1,445
  • 14
  • 30
Prithiv
  • 504
  • 5
  • 20

1 Answers1

2

Try the following code:

private void sample()
{
    int rowIndex = 0;
    int colIndex = 0;
    Dictionary<int[], Image> temp = new Dictionary<int[], Image>();
    int[] rowcol = new int[] { rowIndex, colIndex };


    if (!(temp.Where(k => k.Key == rowcol).Count() > 0))
    {
        animatedImage = style.BackgroundImage;
        temp.Add(rowcol, animatedImage);
    }
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Thomas
  • 1,445
  • 14
  • 30
  • Wow. That will not work because you also compare references. Changing `k.Key == rowcol` to `k.Key.SequenceEqual(rowcol)` might work but you'll lost the advantages of a dictionary over a list. Btw: you iterate over the all values even if the first value matches your contraint. Using `Any()` instead of `Count()` will stop after the first occurance. – Sebastian Schumann Apr 19 '17 at 05:50