简体   繁体   中英

Getting distinct objects from a list

Edit: The problem is not with distinct method but how Title is coded. Comparising with StringComparison.InvariantCultureIgnoreCase retruns true. Problem closed. Here is my code:

var b = ret.DistinctBy(x => new { x.Title, x.Type }).ToList();

在此处输入图片说明

When I run this line with my input I get this. I want to eliminate duplicates based on Title and Type. Can you tell me where I make a mistake? Aren't these 2 objects the same based on my comparison?

Thanks

Edit: Did more debugging. It appears that the names are different.

var z = ret[0].Title == ret[1].Title;

Checked with text comparer. It is the same. Any ideas why? I read MyClippings from Kindle. Will test if they code Title differently.

Can you share a little more code ie the Class using my example below it works correctly:

    public class Test {
        public string Title {get;set;}
        public Type Type {get;set;}
    }

    public enum Type {
        Kindle
    }

    public static void Main()
    {
        var ret = new List<Test> {
            new Test {
                Title = "Book A",
                Type = Type.Kindle
            },
            new Test {
                Title = "Book A",
                Type = Type.Kindle
            }
        };
        var b = ret.DistinctBy(x => new { x.Title, x.Type }).ToList();

        b.ForEach(x => Console.WriteLine(x.Title));
    }

Outputs:
Book A

Runnable Version : https://dotnetfiddle.net/gi8z7j

If you change the second Book A to Book B it outputs:

Book A
Book B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM