I have a bunch of events with their location being pulled from the db and I am doing the following:
List<Place> placeList = new List<Place>();
foreach (var item in eventsList)
{
bool coordinateExist= placeList.Where(x => x.latitude == item.Latitude && x.longitude == item.Longitude).Count()>0;
Place place;
if (coordinateExist)
place = new Place() { title = item.Title, latitude = item.Latitude+0.0001, longitude = item.Longitude};
else
place = new Place() { title = item.Title, latitude = item.Latitude, longitude = item.Longitude};
placeList.Add(place);
}
I have a slight issue though. If two locations have the exact same latitude and longitude I want to offset the latitude by the slightest amount (equiv to a few meters maybe?), and then add it to placeList. Hence I will have a list full of unique coordinates.
how can i achieve this nicely? The above works but not nice IMO
The method you choose to do this will depend on how many items you expect to put into the list and how fast you want your list population to be.
If the list is very small, you can check the list for identical places and then update your latitude, check again, etc. That is:
As you can imagine, that gets hugely expensive if the number of events is large, because you have to search the entire list at least once for every item that you add.
If that becomes too expensive, you can maintain a
HashSetof latitude/longitude pairs, and check it as you’re adding items. Come to think of it, you could just build the thing as aHashSetand then convert it to a list:That still has potential pathological behavior if you have a lot of events with the same latitude/longitude. You can minimize those effects by adding a small random amount when you adjust the latitude. That is, rather than just adding 2 meters or whatever, add a random amount between 1 and 10 meters, for example. Or, you might want to randomly move the longitude, too.
If you were to do as @anon suggested: build the list with the duplicates and then remove them later, you’d end up doing something very similar. That is, you’d probably build a
HashSetof visited locations and test against it while removing the dupes.