如果声明在foreach上

7 .net c# linq

我注意到我做了很多这种模式.有没有更好的方法来写这个?

            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
Run Code Online (Sandbox Code Playgroud)

我知道if sz in tags存在于其他语言中.我希望linq中的某些内容可以提供帮助吗?

Jor*_*dão 13

例如:

if (tags.Contains(sz)) ...
Run Code Online (Sandbox Code Playgroud)

对于更一般的问题:

if (tags.Any(tag => InvolvedLogic(tag))) ...
Run Code Online (Sandbox Code Playgroud)


Ais*_*ina 8

假设tagsList<T>:

if (tags.Contains(sz))
{
  // ...
}
Run Code Online (Sandbox Code Playgroud)