user34537
user34537

Reputation:

if statement on a foreach

I notice i do this pattern a lot. Is there a better way to write this?

            bool hit=false;
            foreach (var tag in tags)
                if (tag == sz)
                {
                    hit = true;
                    break;
                }
            if (hit) continue;
            //tags.add(sz); or whatever i wanted to do

I know if sz in tags exist in other languages. I hope theres something in linq that can help?

Upvotes: 7

Views: 9564

Answers (4)

NetSide
NetSide

Reputation: 3890

if (tags.Any(t=>t == sz) == true)
{
   //...
}

Upvotes: 0

Håvard S
Håvard S

Reputation: 23876

If you just want to know if a given item is in tags, do:

if(tags.Any(t => t == sz))
{
  // Do stuff here
}

If you want to grab a reference to the found item, do:

var foundTag = tags.FirstOrDefault(t => t == sz);
// foundTag is either the first tag matching the predicate,
//  or the default value of your tag type

Upvotes: 2

Jordão
Jordão

Reputation: 56477

For the example:

if (tags.Contains(sz)) ...

For the more general problem:

if (tags.Any(tag => InvolvedLogic(tag))) ...

Upvotes: 13

Aistina
Aistina

Reputation: 12683

Assuming tags is a List<T>:

if (tags.Contains(sz))
{
  // ...
}

Upvotes: 8

Related Questions