使用 groupby 方法按多个属性组合分组,并取每组的第一项即可实现去重。具体做法是传入一个匿名对象作为键,例如 x => new { x.a, x.b},然后调用 .select(g => g.first()) 获取结果。如果输入数据中存在完全相同的复合键记录,它们会被归为一组,最终只保留一条。

GroupBy 如何识别重复的复合键
GroupBy 利用匿名对象的默认相等比较器来识别重复项。当两个对象的指定属性值完全一致时,它们被视为同一个键。这意味着只要参与组合的属性值相同,无论对象的其他属性(如 ID)是否不同,都会被合并到同一组中。

using System;
using System.Collections.Generic;
using System.Linq;
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public int Category { get; set; }
}
public class Program
{
public static void Main()
{
var items = new List<item>
{
new Item { Id = 1, Name = "A", Category = 1 },
new Item { Id = 2, Name = "A", Category = 1 }, // 重复键
new Item { Id = 3, Name = "B", Category = 2 },
new Item { Id = 4, Name = "A", Category = 1 } // 重复键
};
var distinctItems = items.GroupBy(x => new { x.Name, x.Category })
.Select(g => g.First())
.ToList();
foreach (var item in distinctItems)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}, Category: {item.Category}");
}
}
}
</item>
预期输出:
Id: 1, Name: A, Category: 1 Id: 3, Name: B, Category: 2
自定义比较器处理复杂类型
如果需要对更复杂的逻辑进行去重,或者匿名对象无法满足需求,可以实现 IEqualityComparer。通过传入自定义的比较器,可以精确控制哪些属性参与比较以及比较的逻辑。这在处理嵌套对象或需要忽略某些字段时非常有用。

using System;
using System.Collections.Generic;
using System.Linq;
public class ComplexItem
{
public int Id { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
public string ZipCode { get; set; }
}
public class AddressComparer : IEqualityComparer<address>
{
public bool Equals(Address x, Address y)
{
if (x is null || y is null) return false;
return x.City == y.City && x.ZipCode == y.ZipCode;
}
public int GetHashCode(Address obj)
{
if (obj is null) return 0;
return HashCode.Combine(obj.City, obj.ZipCode);
}
}
public class Program
{
public static void Main()
{
var items = new List<complexitem>
{
new ComplexItem { Id = 1, Address = new Address { City = "Beijing", ZipCode = "100000" } },
new ComplexItem { Id = 2, Address = new Address { City = "Beijing", ZipCode = "100000" } }, // 重复
new ComplexItem { Id = 3, Address = new Address { City = "Shanghai", ZipCode = "200000" } }
};
var comparer = new AddressComparer();
var distinctItems = items.GroupBy(x => x.Address, comparer)
.Select(g => g.First())
.ToList();
foreach (var item in distinctItems)
{
Console.WriteLine($"Id: {item.Id}, City: {item.Address.City}, Zip: {item.Address.ZipCode}");
}
}
}
</complexitem>
</address>
预期输出:
Id: 1, City: Beijing, Zip: 100000 Id: 3, City: Shanghai, Zip: 200000
基于程序中某个输入、条件或结果的具体问题
在上面的示例中,当输入包含多个具有相同 Name 和 Category 但不同 Id 的对象时,程序会保留第一个遇到的对象。这是因为 g.First() 总是返回分组中的第一个元素。如果需要保留最后一个,可以改用 g.Last()。这种选择取决于业务逻辑对“去重后保留哪条记录”的定义。










