按字段删除结构列表
本文关键字:列表 结构 删除 字段 | 更新日期: 2023-09-27 18:07:33
我在c#中有一个列表,该列表包含结构,我想删除重复的结构,但只是有一些字段相等的结构。我该怎么做?thx
List<Sample> samples = new List<Sample>(new[]
{
new Sample {Id = 1},
new Sample {Id = 1},
new Sample {Id = 2},
new Sample {Id = 3},
new Sample {Id = 1}
});
var duplicates = samples
.Select ((s, i) => new { s.Id, Index = i }) // Get item key and index
.GroupBy (s => s.Id) // Group by Key
.Where (g => g.Count() > 1) // Get duplicated ones
.SelectMany(g => g.Skip (1) // We'll keep first one
.Select(i => i.Index)) // Get other items ids
.Reverse();
foreach (var index in duplicates)
{
samples.RemoveAt(index);
}
有两种可能的解决方案:
- 手动删除重复项:意味着用嵌套循环遍历列表。
- 为结构体分配哈希码和相等性检查,并使用
Hashset<YourStruct>
删除重复项。这可以通过自定义IEqualityComparer
(链接)实现来完成,或者如果您通过实现IEquatable
接口并适当覆盖GetHashCode
和Equals
方法来"拥有"该结构。
如果你的集合很小,并且这个操作必须在你的代码中执行一次,我会选择解决方案一。但是,如果这种比较逻辑被反复使用,我会选择解决方案二。
方案二的实现:
struct YourStruct
{
public int Id;
}
class Comparer : IEqualityComparer<YourStruct>
{
public bool Equals(YourStruct a, YourStruct b)
{
return a.Id == b.Id;
}
public int GetHashCode(YourStruct s)
{
return s.Id;
}
}
List<YourStruct> list = new List<YourStruct>();
HashSet<YourStruct> hs = new HashSet<YourStruct>(list, new Comparer());