[英]Distinct values list
我正在尝试从列表位置中删除位置。 所有值在顺序上必须彼此唯一。
我问自己我能做的最好的。
位置包含纬度和经度。
List<Location> locations;
Location a,b,c,d;
a = locations[....]
b = locations[....]
c = locations[....]
d = locations[....]
那么我应该如何给a,b,c和d所有唯一值,以使Location彼此不相等?
您应该在类中重写Equals
和GetHashCode
,例如:
public class Location
{
public int Latitude { get; set; }
public int Longitude { get; set; }
public override bool Equals(object obj)
{
if(obj == null)return false;
if(object.ReferenceEquals(this, obj)) return true;
Location l2 = obj as Location;
if(l2 == null) return false;
return Latitude == l2.Latitude && Longitude == l2.Longitude;
}
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + Latitude.GetHashCode();
hash = hash * 23 + Longitude.GetHashCode();
return hash;
}
}
public override string ToString()
{
return string.Format("{0},{1}", Latitude, Longitude);
}
}
现在您已经可以使用Enumerable.Distinct
删除重复项:
var uniqeLocations = locations.Distinct().ToList();
在数组实例上使用Union
方法合并不同的项目(请记住包括using System.Linq
来访问Linq特定的扩展方法):
using System;
using System.Linq;
namespace DistinctValues
{
public struct Location
{
public Location(double longitude, double latitude) : this()
{
this.Longitude = longitude;
this.Latitude = latitude;
}
public double Longitude { get; set; }
public double Latitude { get; set; }
public override string ToString()
{
return string.Format("Longitude: {0}, Latitude={1}", this.Longitude, this.Latitude);
}
}
class Program
{
static void Main(string[] args)
{
var a = new Location[]
{
new Location(123.456, 456.789),
new Location(123.456, 456.789),
new Location(234.567, 890.123),
};
var b = new Location[]
{
new Location(123.456, 456.789),
new Location(890.123, 456.789),
};
// Join array a and b. Uses union to pick distinct items from joined arrays
var result = a.Union(b);
// Dump result to console
foreach(var item in result)
Console.WriteLine(item);
}
}
}
如果您不希望或无法更改Location
类的实现,并且需要获取不同的位置,则可以按纬度和经度对它们进行分组,然后从每个组中选择第一个位置(组中的所有位置都具有相同的纬度和经度):
var distinctLocations = from l in locations
group l by new { l.Latitude, l.Longitude } into g
select g.First();
但是,当然,如果不是需要比较位置的地方,则应该使用@Tim Schmelter解决方案。
更新:获取唯一的随机位置:
Random rnd = new Random();
List<Location> uniqueRandomLocations =
locations.GroupBy(l => new { l.Latitude, l.Longitude })
.Select(g => g.First())
.OrderBy(l => rnd.Next())
.Take(N)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.