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
Asked
Active
Viewed 917 times
0
-
@Rubens Farias, not everything is homework you know. there are even stupid/trivial/easy things in business and sometimes even the top programmers might miss them. – Daniel Sep 06 '11 at 10:24
-
1Can you clarify with an example, not sure if I get the requirement – SWeko Sep 06 '11 at 10:26
-
1http://stackoverflow.com/questions/4542600/interview-question-remove-duplicates-from-an-unsorted-linked-list – CharithJ Sep 06 '11 at 10:28
-
http://stackoverflow.com/questions/9673/remove-duplicates-from-array – CharithJ Sep 06 '11 at 10:29
2 Answers
0
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);
}
Rubens Farias
- 57,174
- 8
- 131
- 162
0
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 theIEquatableinterface with appropriateGetHashCodeandEqualsmethod 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());
Stefan
- 14,530
- 4
- 55
- 62
-
thx!, and if wanted to compare objects from a class instead of structures¿? – jobormo Sep 06 '11 at 14:39
-
about the same. As long as you implement your own `GetHashCode` and `Equals`. – Stefan Sep 06 '11 at 15:10