简体   繁体   中英

Removing duplicates from arraylist which contain array of double

I have a list which has double array whose items are geocordinates,this list has duplicate elements which i need to remove to preserve only unique values

this is what i have tried

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]);
         }
    }
}  

result - my list which has redundant arrays

basically, i need to remove all the arrays inside the list which has same values(x and y geocordinates)

still i have some elements in the list which gets duplicated, can anyone improve my solution please ? would be great help

This example takes the 100 in data down to 41 in dataUnique

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 your code: Do note that comparing float or double will not work well if any computation has been used on those numbers as binary numbers do not allow the precision needed to do the comparisons.. - Do replace the double by decimal as a first improvement..

Using ToString() may or may not help overcome the issue; best not to rely on it..

Try this:

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--;
         }
    }
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM