比较2个列表并从第二个列表中获取不匹配的列表值并将其添加到第一个列表中。 我有两个清单,
清单< 模板 > parent = new Template [] { new Template() {ID =1},新模板(){ID =2},新模板(){ID =3},新模板(){ID =4},新模板(){ID =5},新模板(){ID =6},} .ToList();列表< 模板 > child = new Template [] { new Template(){ID =1}, new Template(){ID =3}, new Template(){ID =5}, new Template(){ID =11},新模板(){ID =12} } .ToList();
我希望父母名单是: 1 2 3 4 br /> 5 6 11 12 怎么做? i这样做了,但它没有用......, parent.AddRange(parent.Except( child).ToList());
解决方案即使你把它反过来也不会起作用: parent.AddRange(child.Except(parent))。ToList();
为什么不呢?因为
模板a = new 模板(){ID = 1}; 模板b = 新模板(){ID = 1};不创建一个实例 - 它创建两个具有相同ID的不同实例 。 比较这些是相同的吗?比较引用,而不是内容,除非Template是结构,所以 a 和 b 是不同的! 你需要使用另一种形式的除外: msdn.microsoft/en-us/library/vstudio/bb336390(v = vs.90).aspx [ ^ ]接受自定义比较器决定平等(并交换孩子/父母)
看到我只举一个例子,我有两个列表具有相同的实例值..., 父母列表有一些值,孩子会有一些价值, i想得到父母没有的价值但是孩子有,那些孩子的价值要添加到父母列表中.....这是我期待的
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,
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();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());
解决方案 That's not going to work, even if you put it the other way round: parent.AddRange(child.Except(parent)).ToList();Why not? Because
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: msdn.microsoft/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)
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更多推荐
比较父母和子女列表
发布评论