简体   繁体   中英

How to get distinct value of Upper and lower case?

I have this function and I want to get distinct value in # Data #. but my problem is if there are two value with the same characters but one is Upper and one is Lower (ie Comedy and comedy) it still have both value Comedy and comedy in my Data. So when I bind to Data...it shows both.

My function is:

public void LoadBookGenre(Book abc)
{
    var loadbook = from Book s in BookDB.Books where s.Genre == abc.Genre select s;
    BookAttribute.Clear();
    foreach (Book m in loadbook) BookAttribute.Add(m);
    List<Book> distinct = BookAttribute.GroupBy(a => a.Genre).Select(g => g.First()).ToList(); 
    Data.Clear(); 
    foreach (Book s in distinct) Data.Add(s);
}

You can use the GroupBy overload that allows you to specify a case-insensitive comparer:

List<Book> distinct = 
    BookAttribute.GroupBy(a => a.Genre, StringComparer.OrdinalIgnoreCase)
                 .Select(g => g.First())
                 .ToList();

Depending on your scenario, you might also be able to use Distinct :

List<string> distinctGenres = 
    BookAttribute.Select(a => a.Genre)
                 .Distinct(StringComparer.OrdinalIgnoreCase)
                 .ToList();

Edit : You also need to alter the equality check in your initial query:

var loadbook = from Book s in BookDB.Books 
               where s.Genre.Equals(abc.Genre, StringComparison.OrdinalIgnoreCase)
               select s;

常见的解决方案是维护使用upper()或lower()强制使用大写或小写字母的字符串的版本,并将该内部字符串用于比较,并将原始字符串用作“显示”版本。

Replace

Data.Add(s);

by

var found = Data.SingleOrDefault(x => x.Genre.ToUpperInvariant() == s.Genre.ToUpperInvariant());
if (found == null)
{
    Data.Add(s);
}

This way, you avoid adding the same name twice, while keeping the casing of the first one you find.

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