-2

I have an object PixelData:

public class PixelData
{
   public int X {get;set;}
   public int Y {get;set;}
}

pixel data is a key to a dictionary.

Dictionary<PixelData, int> dict

how do i use pixel data the right way?

tal
  • 525
  • 2
  • 8
  • 26
  • 9
    Well as you haven't overridden `Equals` or `GetHashCode`, you'd need to have a reference to the original `PixelData` object used as the key. Additionally, even if you *did* override `Equals` and `GetHashCode`, you'd have a mutable key which is generally a bad idea. – Jon Skeet Sep 10 '17 at 14:44

2 Answers2

3

A very simple solution would be to use a struct instead of a class for PixelData:

public struct PixelData
{
    public int X;
    public int Y;
}

var dict = new Dictionary<PixelData, int>();

You can read about the differences between structs and classes in C# here. Short version: structs are value types, unlike classes which are reference types. Therefore, if you want to retrieve a value from the dictionary, you don't need a reference to the original PixelData instance which was used as the key. You can go ahead and create a new instance, with the exact same X and Y you used for the key, and it will work just fine.

// Add new value to dictionary with new PixelData instance as the key
dict.Add(new PixelData { X = 1, Y = 1 }, 42); 

// Retrieving the value using a new, but identical instance of PixelData works just fine
int value = dict[new PixelData { X = 1, Y = 1 }]);
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
-1

If X and Y are public properties, then below query can be used to retrieve the matching dictionary value. This query assumes that 'searchingForItem' is the PixelData Item, you are looking to find in dict.

var matchingItem = dict.FirstOrDefault(p => p.Key.X.Equals(searchingForItem.X) && p.Key.Y.Equals(searchingForItem.Y));