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?
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?
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 }]);
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));