LINQ's Distinct() on a particular property

后端 未结 20 2022
一向
一向 2020-11-21 05:05

I am playing with LINQ to learn about it, but I can\'t figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy

相关标签:
20条回答
  • 2020-11-21 05:53

    Use:

    List<Person> pList = new List<Person>();
    /* Fill list */
    
    var result = pList.Where(p => p.Name != null).GroupBy(p => p.Id).Select(grp => grp.FirstOrDefault());
    

    The where helps you filter the entries (could be more complex) and the groupby and select perform the distinct function.

    0 讨论(0)
  • 2020-11-21 05:53
    List<Person>lst=new List<Person>
            var result1 = lst.OrderByDescending(a => a.ID).Select(a =>new Player {ID=a.ID,Name=a.Name} ).Distinct();
    
    0 讨论(0)
  • 2020-11-21 05:54

    What if I want to obtain a distinct list based on one or more properties?

    Simple! You want to group them and pick a winner out of the group.

    List<Person> distinctPeople = allPeople
      .GroupBy(p => p.PersonId)
      .Select(g => g.First())
      .ToList();
    

    If you want to define groups on multiple properties, here's how:

    List<Person> distinctPeople = allPeople
      .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
      .Select(g => g.First())
      .ToList();
    
    0 讨论(0)
  • 2020-11-21 05:54

    Override Equals(object obj) and GetHashCode() methods:

    class Person
    {
        public int Id { get; set; }
        public int Name { get; set; }
    
        public override bool Equals(object obj)
        {
            return ((Person)obj).Id == Id;
            // or: 
            // var o = (Person)obj;
            // return o.Id == Id && o.Name == Name;
        }
        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }
    

    and then just call:

    List<Person> distinctList = new[] { person1, person2, person3 }.Distinct().ToList();
    
    0 讨论(0)
  • 2020-11-21 05:56

    Please give a try with below code.

    var Item = GetAll().GroupBy(x => x .Id).ToList();
    
    0 讨论(0)
  • 2020-11-21 05:58

    The following code is functionally equivalent to Jon Skeet's answer.

    Tested on .NET 4.5, should work on any earlier version of LINQ.

    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
      this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
      HashSet<TKey> seenKeys = new HashSet<TKey>();
      return source.Where(element => seenKeys.Add(keySelector(element)));
    }
    

    Incidentially, check out Jon Skeet's latest version of DistinctBy.cs on Google Code.

    0 讨论(0)
提交回复
热议问题