Hari Gillala
Hari Gillala

Reputation: 11926

Find duplicates in a list

I have list of books in my application and I am trying to add validation so that duplicate books are not added to the list. The validation should check that the name of the book is not already present in the list, regardless of case i.e. the Lowercase "book1" and the Uppercase "BOOK1" should be treated as the same.

I have written the following code so far:

public string Error
{
    get
    {
        if (Books.Count() != Books.Select(x => new { x.Name.ToUpper(), x.CategoryID }).Distinct().Count())
        {
            return "Every Book and Category should be unique";
        }
        return string.Empty;
    }
}

but it comes up with the following error:

Anonymous Type Projection Initializer Should be simple name or member access expression.

How should I make to check for the cases as well?

Upvotes: 1

Views: 135

Answers (2)

Brent Waggoner
Brent Waggoner

Reputation: 558

You might try using a Dictionary, since they don't allow duplicates, using the name of the book as the key.

Upvotes: 0

Servy
Servy

Reputation: 203825

The issue is in this code segment:

new { x.Name.ToUpper(),

C# doesn't know what property name to give that expression, so you need to be explicit about what this should be called:

new { Name = x.Name.ToUpper(),

Upvotes: 7

Related Questions