LINQ Distinct Query

前端 未结 4 1084
余生分开走
余生分开走 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-14 23:58

    The simplest way to do this is to use GroupBy:

    var uniqueTasks = allTasks.GroupBy(p => p.TypeID);
    

    This will give you a set of groupings that map a TypeID to the tasks with that ID.

    If you want a set of tasks, you can write

    var uniqueTasks = allTasks.GroupBy(p => p.TypeID).Select(g => g.First());
    
    0 讨论(0)
  • 2021-01-15 00:00

    You need to implement your own comparer:

    public class TaskComparer : IEqualityComparer<Task>
    {
    
        #region IEqualityComparer<Task> 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)

    0 讨论(0)
  • 2021-01-15 00:11

    Let me make sure I understand the problem: you have a sequence of tasks called allTasks, and you would like a sequence without duplicates of all the ids, yes?

    Transform the sequence of tasks into a sequence of ids:

    var ids = allTasks.Select(p=>p.TypeId);
    

    Now you have a sequence of ids. You wish to filter out the duplicates from that sequence:

    var distinctIds = ids.Distinct();
    

    And you're done. Is that what you were after?

    0 讨论(0)
  • 2021-01-15 00:21
     var uniqueTasks = allTasks.Select(t=>t.TypeName).Distinct().ToList();
    
    0 讨论(0)
提交回复
热议问题