[英]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.