How to check if an entry in a C # list exists using a search method

I am using C # List with the Find method as follows:

Tag searchResult = tags.Find(x => x.TagId.Equals(tag));

The list contains a "struct tag", now my problem is how to check if a tag entry exists in the list.

In the MSDN section, I found the following:

  • If nothing is found, the "default value for type T" will be returned.

So, I tried the following:

if(default(Tag) == searchResult ){}

But this does not work due to an error: "Operator" == "cannot be applied to operands of type"

How am I wrong?

+4
source share
3 answers

Tag - struct, default(Tag) , , Tag Tag, /, default(Tag).

(An .Any(), .First()), , . , , Nullable<T>, struct:

public static T? FirstOrNull<T>(this IEnumerable<T> items, Func<T, bool> predicate) where T : struct
{
    foreach(var item in items)
    {
        if (predicate(item))
            return item;
    }

    return null;
}

, :

Tag? searchResult = tags.FirstOrNull(x => x.TagId.Equals(tag));
if (searchResult != null)
{
    //do something with your search result
}

, Nullable<Tag> ( Tag?), .HasValue, .Value .GetValueOrDefault(), .


EDIT: , , , , . , , , , - , ( , ), .

+1

.

Enumerable.Any():

if (tags.Any(x => x.TagId.Equals(tag)))
{
    // There a match.
}

, , Enumerable.FirstOrDefault:

var tag = tags.FirstOrDefault(x => x.TagId.Equals(tag));
if (tag != null) 
{
    // There exists a tag.
}
+5

, , Contains() System.Linq:

bool exists = tags.Contains(tag);

. , ( ). IEqualityComparer, , .

0

Source: https://habr.com/ru/post/1599106/


All Articles