I’ve done a bunch of Lat/Long type mapping programs over the years and one of the problems always ends up around performance. A common problem is that you keep redrawing the same line over and over and over. The pixels you are drawing don’t get any darker so all you are doing is wasting time. In my current project, we were drawing approximately 1500 lines when we really only had about 150 unique lines. I’ve always known how to solve this problem with a bunch of thrown together hacked up code, but now, LINQ gives me a very clean way to do it.
So, the problem is you have a record that looks like this:
public class LoadSegmentInfoFlat { public double? OriginLattitude { get; set; } public double? OriginLongitude { get; set; } public double? DestinationLattitude { get; set; } public double? DestinationLongitude { get; set; } public string Color { get; set; } }
You’ve created a list of these and defined it as follows:
var loadSegmentInfoFlats = new List<LoadController.LoadSegmentInfoFlat>();
Now, you want to create a unique list of Lattitude, Longitude Origins and Destinations by color.
The LINQ query that does the trick is a simple group by that creates an anonymous result (which is our answer). Here is the LINQ query (thanks to my friend in the MSDN LINQ Forums, Lignzhi Sun).
var segments = from a in loadSegmentInfoFlats group a by new { a.OriginLattitude, a.OriginLongitude, a.DestinationLattitude, a.DestinationLongitude, a.Color } into grouplist select new { grouplist.Key.OriginLattitude, grouplist.Key.OriginLongitude, grouplist.Key.DestinationLattitude, grouplist.Key.DestinationLongitude, grouplist.Key.Color, Count = grouplist.Count() };
The resulting segments in Visual Studio 2008 debugger are as follows:
Hope this helps!