15,793,547 members
See more:
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".
C#
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();
}

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;

Posted
Updated 2-Nov-12 15:19pm
v4
KEL3 2-Nov-12 8:25am
You mean that you want countTrue to return 1 when data contains "W" else return 0 ?
If you write a normal for/foreach loop that does what you want perhaps I could give you the LINQ equivalent (if it exists).
Or give examples of input and output.

You say:
data={"W","H","X","V"} => return 3
data={"O","H","X","V"} => return 1
???

I don't understand what is countTrue() supposed to count...
D-Kishore 5-Nov-12 5:53am
Here counttrue() counts the non matched "W".
in the above given example will return 3.

## Solution 1

I think this is better

C#
public int countTrue(string[] data, string X)
{
bool results = data.Any(A=>!A.Equals(X,StringComparison.OrdinalIgnoreCase));
return results?1:0;
}

## Solution 2

It sounds like you want the first element that does not contain a 'W' so this is what you want:

C#
public string FirstNonMatch(string[] data, string X)
{
return data.FirstOrDefault(i => ! i.Contains(X));
}

v2
dmunisubbu 3-Nov-12 5:36am
public int countTrue(string[] data, string X)
{

//var results = from p in data
//where !p.Contains(X)
//select p;
var results= data.FirstOrDefault(i => !i.Contains(X));

return results.Count();
}
D-Kishore 5-Nov-12 5:53am
Thank you so much nelson.
My 5+
Clifford Nelson 5-Nov-12 11:12am
Happy to oblige. Linq is quite powerful, but can be very confusing (try doing a distinct). It is probably one of the best tools around since it saves so many lines of code.