使用linq检索具有重复项的两个列表之间的差异

时间:2014-04-16 11:52:39

标签: c# linq

我有两个列表,其中只包含我从不同来源获得的重复项。

//Duplicate 1
var Duplicate1 = list1.GroupBy(d => new { d.Name, d.Value })
    .Where(dup => dup.Count() > 1).SelectMany(dup => dup);

返回:{{red, red}, {red, red}, {green, green}, {green, green}}

//Duplicate 2
var Duplicate2 = list2.GroupBy(d => new { d.Name, d.Value })
    .Where(dup => dup.Count() > 1).SelectMany(dup => dup);

返回:{{red, red}, {red, red}, {green, green}, {green, green}, {green, green}}

我如何使用linq对这些列表进行排序,以便我所拥有的只是{green, green}的差异?

1 个答案:

答案 0 :(得分:4)

创建两个查找,然后加入这些查找,检查哪个查找对具有最多的项目,然后获取等于差异的多个项目:

var al = Duplicate1.ToLookup(x => x);
var bl = Duplicate2.ToLookup(x => x);

var result = al.Join(bl,  agrp        => agrp.Key, 
                                bgrp  => bgrp.Key,
                         (agrp, bgrp) => agrp.Count() > bgrp.Count() ?
                                         agrp.Take(agrp.Count() - bgrp.Count()) :
                                         bgrp.Take(bgrp.Count() - agrp.Count()))
                .SelectMany(x => x);