Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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;


Please give me you ideas.
Posted
Updated 2-Nov-12 14:19pm
v4
Comments
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.

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;
       }
 
Share this answer
 
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));
}
 
Share this answer
 
v2
Comments
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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900