I use .NET 3.5 framework, so no tuples. I have many use cases where I have to create a custom key for a dictionary. How can I make this better?
public class CompositeKey<T>
{
public T Content { get; set; }
public Func<T, object>[] Lambdas { get; set; }
public CompositeKey(T obj, params Func<T, object>[] propLambdas)
{
Content = obj;
Lambdas = propLambdas;
}
public override int GetHashCode()
{
int hash = 0;
foreach (var l in Lambdas)
{
hash ^= l(Content).GetHashCode();
}
return hash;
}
public override bool Equals(object obj)
{
bool isEqual = true;
if (obj is T)
{
T o = (T)obj;
foreach (var l in Lambdas)
{
isEqual &= (l(Content) == l(o));
}
return isEqual;
}
return false;
}
}
public class TestCode
{
public void somemethod()
{
Dictionary<CompositeKey<TestPOCO>, string> dict = new Dictionary<CompositeKey<TestPOCO>, string>();
var t1 = new TestPOCO() { ID=1, Name="A" };
var t2 = new TestPOCO() { ID = 2, Name = "B" };
dict.Add(new CompositeKey<TestPOCO>(t1, x => x.ID, x => x.Name) , t1.Name);
dict.Add(new CompositeKey<TestPOCO>(t2, x => x.ID, x => x.Name), t2.Name);
}
}
public class TestPOCO
{
public int ID;
public string Name;
}
Especially this part:
dict.Add(new CompositeKey<TestPOCO>(t1, x => x.ID, x => x.Name) , t1.Name);
dict.Add(new CompositeKey<TestPOCO>(t2, x => x.ID, x => x.Name), t2.Name);
The challenge is to have lambda defined only once, but have different key objects based on the POCO.