Delete list of structures by field
I have a list in c#, that list contains structures, I would like to delete repeated 开发者_开发百科structures, but just the structures which have some fields equal. How Can I do? 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);
}
There are two possible solution:
- Remove the duplicates by hand: meaning iterate through the list with a nested loop.
- Assign the struct a hash code and equality check and use a
Hashset<YourStruct>
to remove the duplicates. This can be done by a customIEqualityComparer
(link) implementation or if you "own" the struct by implementing theIEquatable
interface with appropriateGetHashCode
andEquals
method overriding.
If your set is small and this operation has to be done once in your code, I would go for solution one. But if this comparison logic is used over and over again I would go for solution two.
Implementation for solution two:
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());
精彩评论