6

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 ?

1
  • 2
    not sure why you are using tuples here, with 6 properties, you definitely need a class. Oct 8, 2017 at 13:34

3 Answers 3

10

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

4

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;
        }
    }
}        
2
  • Thank you, this is really usefull. I assume i can also add an if statement for the property within the Equals check? so if 2 coordinates are the same, and the property different, i always want to keep the one "ArcStart" and not the "LineEnd" ?
    – Dante1986
    Oct 8, 2017 at 13:49
  • @Dante1986 yes, you can define Equals method as you want
    – Backs
    Oct 8, 2017 at 13:53
4

You can use DistinctBy method in MoreLINQ library.

points.DistinctBy(c => new {c.Item1, c.Item2, c.Item3}).ToList();

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.