tags:

views:

278

answers:

4

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?

+8  A: 

Assuming tags is a List<T>:

if (tags.Contains(sz))
{
  // ...
}
Aistina
sweet this seems to work on any IEnumerable object!
acidzombie24
Any `ICollection<T>` actually, but yes.
Aistina
+12  A: 

For the example:

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

For the more general problem:

if (tags.Any(tag => InvolvedLogic(tag))) ...
Jordão
I think your assumption is more correct.
ChaosPandion
+2  A: 

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
Håvard S
+2  A: 
if (tags.Any(t=>t == sz) == true)
{
   //...
}
NetSide
Not as efficient as Any - this will walk all the items even when it's already got one.
Ruben Bartelink
Yes you are right. I wrote it as an alternative.
NetSide
Indeed; don't do this. If someone says "do you have any money?" you don't have to count the bills in your pocket to give an answer, you just need to see if there are any.
Eric Lippert
@NetSide: But it's a **very bad** alternative. Do you want people to compete to come up with the worst possible 'alternatives' ? I don't get your point.
Ruben Bartelink
I will never understand why people tend to compare logical value to true instead just writing if (condition) ...
Matajon
@Matajon, the explanation is straightforward. I would guess that over 95% of the "if" statements a beginner programmer sees are of the form "if(TESTEXPRESSION CONDITIONALOPERATOR VALUE)" -- if(i == 10), if (j > 20), and so on. It is very natural to internalize that the "if pattern" always has an expression, an operator, and a value, even though that's not actually a requirement of the language. Most people do not program by learning the formal language spec; they start with a technique they already know and extend it; sometimes that entails writing code that is more verbose than necessary.
Eric Lippert