[英]Removing duplicates from arraylist which contain array of double
我有一個具有雙精度數組的列表,其項是地理坐標,此列表具有重復的元素,我需要刪除這些元素以僅保留唯一值
這就是我嘗試過的
IList<double[]> result = new List<double[]>(); /list declaration
// result gets value from a soap call
for (int i = 0; i < result.Count; i++)
{
for (int j = 0; j < result.Count; j++)
{
if (result[i][0].ToString() == result[j][0].ToString() || result[i][1].ToString() == result[j][1].ToString())
{
result.Remove(result[j]);
}
}
}
結果-我的列表中有多余的數組
基本上,我需要刪除列表中具有相同值(x和y地理坐標)的所有數組
我仍然在列表中有一些元素被重復,有人可以改善我的解決方案嗎? 會很大的幫助
本示例將data
的100減少到dataUnique
41
Random r = new Random(99);
var data = new List<Tuple<decimal, decimal>>();
for (int i = 0; i < 100; i++)
{
data.Add(new Tuple<decimal, decimal>(r.Next(7)/100m, r.Next(7)/100m));
}
var dataUnique = data.Distinct().ToList();
WRT代碼:請注意,比較float
或double
,如果任何計算已被用於對這些數字的二進制數不允許做比較,所需要的精度將無法正常工作。 -不要更換double
用decimal
作為第一改進..
使用ToString()
可能會也可能無法解決該問題; 最好不要依靠它。
嘗試這個:
result = result.GroupBy(r => new { val1 = r[0], val2 = r[1] })
.Select(g => new double[] { g.Key.val1, g.Key.val2 }).ToList();
IList<double[]> result = new List<double[]>(); /list declaration
// result gets value from a soap call
for (int i = 0; i < result.Count; i++)
{
for (int j = i + 1; j < result.Count; j++)
{
if (result[i][0].ToString() == result[j][0].ToString() && result[i][1].ToString() == result[j][1].ToString())
{
result.Remove(result[j]);
j--;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.