c# find nearest match to array of doubles

Posted by Scott on Stack Overflow See other posts from Stack Overflow or by Scott
Published on 2010-04-15T19:49:55Z Indexed on 2010/04/15 19:53 UTC
Read the original article Hit count: 875

Filed under:
|

Given the code below, how do I compare a List of objects's values with a test value?

I'm building a geolocation application. I'll be passing in longitude and latitude and would like to have the service answer back with the location closest to those values.

I started down the path of converting to a string, and formatting the values down to two decimal places, but that seemed a bit too ghetto, and I'm looking for a more elegant solution.

Any help would be great.

Thanks, Scott

public class Location : IEnumerable
{
    public string label { get; set; }
    public double lat { get; set; }
    public double lon { get; set; }

    //Implement IEnumerable
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }

}
[HandleError]
public class HomeController : Controller
{
    private List<Location> myList = new List<Location>
 {             
    new Location {
        label="Atlanta Midtown", 
        lon=33.657674, 
        lat=-84.423130},
    new Location {
        label="Atlanta Airport", 
        lon=33.794151, 
        lat=-84.387228},
    new Location {
        label="Stamford, CT", 
        lon=41.053758, 
        lat=-73.530979}, ...
}
 public static int Main(String[] args)
 {
     string inLat = "-80.987654";
     double dblInLat = double.Parse(inLat);

     // here's where I would like to find the closest location to the inLat
     // once I figure out this, I'll implement the Longitude, and I'll be set
 }

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET