简体   繁体   中英

Verify if string exists in an List

I have a list with "Owners". I need to check if the current user is the owner. so i tried : (list.Contains(string)) :

    string Owner = user.Name.ToString();
    if (lstOwners.Contains(Owner))
    {
        btnManager.Visible = true;
    } //does not work.

It doesn't work !!

but it works when i do that :

    if (lstOwners.Contains("BRJesusCA2"))
    {
        btnManager.Visible = true;
    }

can you please tell me why ??

Owner and "BRJesusCA2" have the same value!

C# is case sensitive

bool contains = lstOwners.Contains(Owner, StringComparer.OrdinalIgnoreCase);
btnManager.Visible = contains;

Since you've asked for a collection that is more efficient. With 90 items that is mirco-optimization. However, you can replace it with a HashSet<string> :

HashSet<string> owners = new HashSet<string>(lstOwners, StringComparer.OrdinalIgnoreCase);
bool isOwner = owners.Contains(Owner);

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

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