.net - How to compare list of X to list of Y in C# by using generics? -


i have 2 classes, x , y. both classes have same similar property 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 x , y; similar structure, , decide create generic class problem.

i have list of x , y , want compare them t1; 1 property, find out element exist on both list, element exist on x , on y.

how can this?

the best thing first create interface contains t1 only. inherit each class x , y interface. can create generic classes or helper classes based on interface.

alternatively, may use reflection, or if use c# 4.0, can use dynamic. classic reflection way slow (large) lists, unless cache method calls, shouldn't take approach. c# 4.0 however, provided method caching through dlr, sufficiently fast in cases.

alternatively (2): when want "right" , want compare lists using standard mechanisms linq, should implement icomparable. can combinee generics create type-safety.

// interface, inherit icomparable public interface ix : icomparable<ix> {     string t1 { get; set; } }  // create 1 base class class xbase : ix {     public string t1 { get; set; }     public int compareto(ix obj)     {         return this.t1.equals(obj.t1);     } }  // inherit others base class class x : xbase {     public string t2 { get; set; }     public string t3 { get; set; } }  class y : xbase {     public string t2 { get; set; }     public string t3 { get; set; }      public strign o1 { get; set; } } 

there many other ways. last method above has advantage of once writing logic t1 , compareto, saves clutter , creates clarity in code.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -