Reputation:
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
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
Reputation: 56477
For the example:
if (tags.Contains(sz)) ...
For the more general problem:
if (tags.Any(tag => InvolvedLogic(tag))) ...
Upvotes: 13