Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List distinct on tuple properties

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 ?

like image 425
Dante1986 Avatar asked Oct 08 '17 13:10

Dante1986


3 Answers

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

like image 122
Aleks Andreev Avatar answered Sep 21 '22 21:09

Aleks Andreev


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;
        }
    }
}        
like image 30
Backs Avatar answered Sep 17 '22 21:09

Backs


You can use DistinctBy method in MoreLINQ library.

points.DistinctBy(c => new {c.Item1, c.Item2, c.Item3}).ToList();
like image 32
Ufuk Hacıoğulları Avatar answered Sep 19 '22 21:09

Ufuk Hacıoğulları