-2

I want this output in list3I have two list with Custom Data Type

list1 = {A, B, C, D} 
 [enter image description here][1]
list2 ={ X, A, B, Y} 

Then I need to remove A, B from list1 and Add A and B from list2 with list1.

list3 = { A(list2), B(list2), C(list1), D(list1)}



See Above Image, I want those items whose ts_key = 0 and if those records are already in list then get ts_key <> 0 for repeated record

4 Answers4

0
list1.Union(list2).ToList();

This may help ..try it

Satish
  • 41
  • 2
  • It is not union operation, it is intersect operation, but common element from list2 merged with list1 and remove common elements from list1 – saleem shaikh Dec 26 '16 at 10:03
  • This is close, except it will also add elements in `list2` that are not in `list1`, where OP just wants to replace instances of objects in `list1` with their `list2` counterparts. – Abion47 Dec 26 '16 at 10:54
0

try this:

List<T> list3=new List<T>
foreach(var item in list1)
{
   if(list2.Contains(item))
   {
      list3.Add(list2.First(x=>x.id==item.id)) //considering id is key
   }
   else
   {
      list3.Add(item);
   }
}
Anup Sharma
  • 2,053
  • 20
  • 30
0

You could first join your two lists. That gives you exactly the intersection of two collections:

var lst = list1.Join(list2, tr => tr.tr_key, tr => tr.tr_key, (x,y)=>y).ToList();

After that you could add to this list all the values from the first list, that are not in the second list. For that you actually need an EqualiyComparer (I assume name of your class as tr):

public class tr_comparer: IEqualityComparer<tr>
{
    public bool Equals(tr x, tr y)
    {
        return x.tr_key == y.tr_key;
    }

    public int GetHashCode(tr obj)
    {
        return obj.tr_key.GetHashCode();
    }
}

After you define a comparer you could execute Except:

lst.AddRange(list1.Except(list2, new tr_comparer()));
Sefe
  • 13,731
  • 5
  • 42
  • 55
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
0

So you want to pick the common elements from list2 and everything else from list1. It sounds like you might be able to pull this off if you perform both a Difference and an Intersection

var list3 = new List<CustomType>();
list3.AddRange(list1.Except(list2));
list3.AddRange(list2.Intersect(list1));
Abion47
  • 22,211
  • 4
  • 65
  • 88