Filter duplicates from a list

I have a List<Location> locations .

The Location class has the Coordinates property - accept string.

How to remove locations with duplicate coordinates and put them in a separate list? It has two lists - one for duplicates and one without.

+4
source share
2 answers

Creating IEqualityComparer <Locations> will be one of your first tasks (allowing you to compare objects based on your chosen properties).

If you want to get unique elements with Linq, you can use the Distinct () method.

You can then remove items from the original list that will leave you with a collection of duplicates.

 var distinctObjects = originalList.Distinct(); var duplicateList = originalList.Except(distinctObjects); 

You will need to use your own comparison comparisons for different, but not for exceptions.

+4
source

It depends on what you mean. If you need one representative list and another for the remaining duplicates, you can do:

 var locationsByCoordinates = locations.ToLookup(location => location.Coordinates); var distinct = locationsByCoordinates.Select(group => group.First()) .ToList(); var duplicates = locationsByCoordinates.SelectMany(group => group.Skip(1)) .ToList(); 

On the other hand, if you need one list for those elements that are unique, and another for those that are not:

 var distinct = locationsByCoordinates.Where(group => group.Count() == 1) .Select(group => group.Single()) .ToList(); var duplicates = locationsByCoordinates.Where(group => group.Count() != 1) .SelectMany(group => group) .ToList(); 

This is a bit inefficient, as it lists twice. Something like this would be slightly better:

 var distinct = new List<Location>(); var duplicates = new List<Location>(); foreach(var group in locationsByCoordinates) { var target = group.Count() == 1 ? distinct : duplicates; target.AddRange(group); } 
+3
source

Source: https://habr.com/ru/post/1338715/


All Articles