Reputation: 1076
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
Upvotes: 0
Views: 80
Reputation: 54453
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..
Upvotes: 2
Reputation: 121
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--;
}
}
}
Upvotes: 1
Reputation: 633
Try this:
result = result.GroupBy(r => new { val1 = r[0], val2 = r[1] })
.Select(g => new double[] { g.Key.val1, g.Key.val2 }).ToList();
Upvotes: 1