Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Compare 2 list and get the not matched list values from 2nd list and add it into the 1st list.

I have two list,

XML
List<Template> parent =  new Template[] {
           new Template(){ID = "1"},
           new Template(){ID = "2"},
           new Template(){ID = "3"},
           new Template(){ID = "4"},
           new Template(){ID = "5"},
           new Template(){ID = "6"},
       }.ToList();


XML
List<Template> child = new Template[] {
           new Template(){ID = "1"},
           new Template(){ID = "3"},
           new Template(){ID = "5"},
               new Template(){ID = "11"},
               new Template(){ID = "12"}
       }.ToList();


im expecting the parent list to be:
1
2
3
4
5
6
11
12

how to do this?

i did in this way, but its not working...,
parent.AddRange(parent.Except(child).ToList());
Posted

That's not going to work, even if you put it the other way round:
C#
parent.AddRange(child.Except(parent)).ToList();

Why not? Because
C#
Template a = new Template(){ID="1"};
Template b = new Template(){ID="1"};
Does not create one instance - it creates two different instances that have the same ID.The comparison for "are these the same?" compares the references, not the content, unless Template is a struct, so a and b are different!

You would need to use the other form of Except: http://msdn.microsoft.com/en-us/library/vstudio/bb336390(v=vs.90).aspx[^] which accepts a custom comparer to decide on equality (and swap child / parent over as well)
 
Share this answer
 
see i just give an example, i have two list with have same instance values...,

parent list have some values and child will have some values,

i want to get what are the values parent dont have but the child have, those child values to be added in parent list..... this is wht im expecting
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900