开发者

if statement on a foreach

开发者 https://www.devze.com 2022-12-18 08:00 出处:网络
I notice i do this pattern a lot. Is there a better way to write this? bool hit=false; foreach (var tag in tags)

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 ca开发者_运维问答n help?


For the example:

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

For the more general problem:

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


Assuming tags is a List<T>:

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号