BlueCompany
BlueCompany

Reputation: 72

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();

enter image description here

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.

Upvotes: 0

Views: 87

Answers (1)

Lee Stevens
Lee Stevens

Reputation: 482

Can you share a little more code i.e 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

Upvotes: 1

Related Questions