字符串not contains(“")中断查询并在C#中使用Linq获取结果
问题描述:
尊敬的专家,
在我的C#Windows应用程序"中,
我有一个字符串[].
我需要一个linq查询,其中string []数据的计数不包含"W".
Dear Experts,
In My C# windows application,
i am having one string[].
i need A linq query that the count of string[] data not contains "W".
string[] data={"W","H","X","V"}
string X="W";
countTrue(data,X);
public int countTrue(string[] data, string X)
{
var results = from p in data
where !p.Contains(X)
select p;
return results.Count();
}
使用上面的代码,我得到的结果数为3.
到这里为止都很好.
我的主要要求是,当string []数据不包含"W"时,我的意思是,当linq正确时,linq应该会中断,结果count = 1;
请给我您的想法.
with the above code i am getting results count=3.
up to here its working fine.
My main requirement is like when the string[] data does not contains "W", i mean when its got true immdiatly linq should break and results count=1;
Please give me you ideas.
答
我认为这样比较好
I think this is better
public int countTrue(string[] data, string X)
{
bool results = data.Any(A=>!A.Equals(X,StringComparison.OrdinalIgnoreCase));
return results?1:0;
}
听起来您想要第一个不包含"W"的元素,所以这就是您想要的:
It sounds like you want the first element that does not contain a ''W'' so this is what you want:
public string FirstNonMatch(string[] data, string X)
{
return data.FirstOrDefault(i => ! i.Contains(X));
}