I have 2 classes, X and Y. Both classes have same similar property like below.
class X
{
public string T1 { get; set; }
public string T2 { get; set; }
public string T3 { get; set; }
}
class Y
{
public string T1 { get; set; }
public string T2 { get; set; }
public string T3 { get; set; }
public string O1 { get; set; }
}
I’ve couple hundreds classes similar to X and Y; similar structure, and I decide to create generic class for this problem.
I have list of X and Y and I want to compare them by T1; only 1 property, to find out which element exist on both list, which element exist only on X and only on Y.
How can I do this?
The best thing to do is to first create an interface that contains
T1only. Then you inherit each class likeXandYfrom this interface. Now you can easily create your generic classes or any helper classes based on this interface.Alternatively, you may use reflection, or if you use C# 4.0, you can use
dynamic. Classic reflection is way to slow for (large) lists, so unless you cache your method calls, you shouldn’t take that approach. C# 4.0 however, provided method caching through the DLR, which is sufficiently fast in most cases.Alternatively (2): when you want to do this “right” and you want to compare the lists using standard mechanisms like LINQ, you should implement IComparable. You can combinee that with generics to create type-safety.
There are many other ways. The last method above has the advantage of only once writing the logic for
T1andCompareTo, which saves from clutter and creates clarity in your code.