LINQ Distinct Query

前端 未结 4 1164
余生分开走
余生分开走 2021-01-14 23:23

I have a C# application that loads a List of CLR objects called \"Tasks\". Each Task has the following properties:

public int ID { get; set; }
public int Typ         


        
4条回答
  •  無奈伤痛
    2021-01-15 00:00

    You need to implement your own comparer:

    public class TaskComparer : IEqualityComparer
    {
    
        #region IEqualityComparer Members
    
        public bool Equals(Task x, Task y)
        {
            return x.TypeID == y.TypeID && x.TypeName == y.TypeName;
        }
    
        public int GetHashCode(Task obj)
        {
            return obj.TypeID.GetHashCode() + obj.TypeName.GetHashCode();
        }
    
        #endregion
    }
    

    Then use it like this:

    var uniqueTasks = allTasks.Distinct(new TaskComparer());
    

    EDIT: Hacked out some GetHashCode() thanks to Slaks who pointed out that GetHashCode is absolutely necessary (I guess it builds a HashTable internally)

提交回复
热议问题