Question

I have two lists of object T. Each T has unique key "T.key"

List<T> List1;
List<T> List2;

I want to create a list of keys of all the objects that are only in List2 but also ones that are in both lists but have specific property differences (lets name them T.a and T.b). Also the list contents are not necessarily in the same order.

Example input/output:

List1 = {{key:1,a:10,b:10,c:10}, {key:2,a:10,b:10,c:10}, {key:3,a:10,b:10,c:10}}
List2 = {{key:1,a:10,b:10,c:99}, {key:2,a:11,b:10,c:10}, {key:4,a:10,b:10,c:10}}

Result = {2,4}
Was it helpful?

Solution 2

this produces your expected output:

 List<T> list1 = new List<T> { new T { key = 1, a = 10, b = 10, c = 10 }, new T { key = 2, a = 10, b = 10, c = 10 }, new T { key = 3, a = 10, b = 10, c = 10 } };
 List<T> list2 = new List<T> { new T { key = 1, a = 10, b = 10, c = 99 }, new T { key = 2, a = 11, b = 10, c = 10 }, new T { key = 4, a = 10, b = 10, c = 10 } };

 List<int> difference = new List<int>();

 foreach (var item2 in list2)
 {
     var item1 = list1.FirstOrDefault(i => i.key == item2.key);

     if (item1 != null)
     {
         if (item2.a == item1.a && item2.b == item1.b)
             continue;
     }           

     difference.Add(item2.key);
 }

difference contains {2,4}

OTHER TIPS

A complete sample that produces the expected keys of: 2 and 4

List<F> L1 = new List<F>{new F(1,10,10,10), new F(2,10,10,10), new F(3,10,10,10)};
List<F> L2 = new List<F>{new F(1,10,10,99), new F(2,11,10,10), new F(4,10,10,10)}; 

void Main() { // Client code. One call covers the biz logic (and sample output)
    // Must call Except on L2 with L1 as the arg for proper eval of biz logic
    foreach ( var item in L2.Except(L1, new CompareListsOfObjsF()) ) 
        Console.WriteLine("key: " + item.key);  
}

class F { // Quick, dirty sample POCO w/ constructor
    public int key, a, b, c; 
    public F(int mk, int ma, int mb, int mc) { key=mk; a=ma; b=mb; c=mc; }
} 

class CompareListsOfObjsF : IEqualityComparer<F> {
    // business-specific equality logic - notice that 'c' is not evaluated
    public bool Equals(F x, F y) {
        return  x.key == y.key && x.a == y.a && x.b == y.b;
    }
    // The logic will not work without a proper hash function:
    public int GetHashCode(F x) { unchecked { // Overflow is ok
            int h = 17 * 23 + x.key;
            h += h * 23 + x.a;
            h += h * 23 + x.b;
            return h; // c has to be left out for selection biz logic to work
      }
   } 
}

OUTPUT:

key: 2

key: 4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top