I have a list of Tuples that looks like this:
List<Tuple<double, double, double, string, string, string>> myList;
The double values represent X-Y-Z cooridinate values, and the strings are certain properties that are attached to these coordinates.
Now i want to use the myList.lis.Distinct().ToList()
method to filter out any duplicates. After all, 1 coordinate can be the start of a line, while another is the endpoint of another line, but as they are connected i get the point XYZ point twice in my list, but with other string properties.
But i only want to use the Distinct on the 3 double values of the Tuple and ignore the strings.
So far i haven't figured out yet how to do so. Is this possible, and how so ?
You can use GroupBy
linq method like this:
var result = myList.GroupBy(x => new {x.Item1, x.Item2, x.Item3})
.Select(x => x.First())
.ToList();
Demo is here
Create new class and override Equals
method to use coordinates only:
class Point
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public string Property1 { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as Point);
}
protected bool Equals(Point other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
return hashCode;
}
}
}
You can use DistinctBy method in MoreLINQ library.
points.DistinctBy(c => new {c.Item1, c.Item2, c.Item3}).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With