当第一个、第二个或两个属性相等(在列表中出现多次)时,尝试从列表中删除重复项。使用 MoreLINQ,下面的代码正在运行:
var list = new List<LinqTest> // LinqTest: object containing 2 strings
{
// are ok
new LinqTest { Str1 = "a1", Str2 = "b1"},
new LinqTest { Str1 = "a2", Str2 = "b2"},
new LinqTest { Str1 = "a3", Str2 = "b3"},
new LinqTest { Str1 = "a5", Str2 = "b5"},
new LinqTest { Str1 = "a6", Str2 = "b6"},
new LinqTest { Str1 = "x1", Str2 = "y1"},
new LinqTest { Str1 = "y1", Str2 = "x1"},
// must be removed
new LinqTest { Str1 = "d1", Str2 = "b4"},
new LinqTest { Str1 = "d1", Str2 = "d2"},
new LinqTest { Str1 = "d1", Str2 = "d2"},
new LinqTest { Str1 = "a4", Str2 = "d2"},
new LinqTest { Str1 = "d3", Str2 = "b7"},
new LinqTest { Str1 = "d3", Str2 = "b8"},
new LinqTest { Str1 = "d3", Str2 = "b8"},
};
var duplicatesStr1 = list
.GroupBy(x => x.Str1)
.Where(x => x.Count() > 1)
.SelectMany(x => x)
.ToList();
var duplicatesStr2 = list
.GroupBy(x => x.Str2)
.Where(x => x.Count() > 1)
.SelectMany(x => x)
.ToList(); ;
var res = list
.ExceptBy(duplicatesStr1, x => x.Str1)
.ExceptBy(duplicatesStr2, x => x.Str2);
var rem = duplicatesStr1
.Union(duplicatesStr2)
.DistinctBy(x => new { x.Str1, x.Str2})
.ToList();
Console.WriteLine("----------");
foreach (var linqTest in res)
{
Console.WriteLine("keep> " + linqTest.Str1 + "-" + linqTest.Str2);
}
Console.WriteLine("----------");
foreach (var linqTest in rem)
{
Console.WriteLine("remove> " + linqTest.Str1 + "-" + linqTest.Str2);
}
问题: 是否有更有效和/或更短的方法来实现这一目标?