Distinct not working with LINQ to Objects

后端 未结 9 1805
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 12:20
class Program
{
    static void Main(string[] args)
    {
        List books = new List 
        {
            new Book
            {
                


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 12:47

    You can achieve this with two ways:

    1. You may to implement the IEquatable interface as shown Enumerable.Distinct Method or you can see @skalb's answer at this post

    2. If your object has not unique key, You can use GroupBy method for achive distinct object list, that you must group object's all properties and after select first object.

    For example like as below and working for me:

    var distinctList= list.GroupBy(x => new {
                                Name= x.Name,
                                Phone= x.Phone,
                                Email= x.Email,
                                Country= x.Country
                            }, y=> y)
                           .Select(x => x.First())
                           .ToList()
    

    MyObject class is like as below:

    public class MyClass{
           public string Name{get;set;}
           public string Phone{get;set;}
           public string Email{get;set;}
           public string Country{get;set;}
    }
    

    3. If your object's has unique key, you can only use the it in group by.

    For example my object's unique key is Id.

    var distinctList= list.GroupBy(x =>x.Id)
                          .Select(x => x.First())
                          .ToList()
    

提交回复
热议问题