I currently have a LINQ statement which works fine with Method Syntax. Am curious to see how would the equivalent query syntax look like. Tried doing multiple iterations but couldn't succeed with query syntax
Currently I have 2 strings - one being a sentence and other being an alphabet. I convert both of them into character for comparison - so I can find the number of occurrences of the character in the full string.
string sentenceToScan = "I Love StackOverflow!!!!";
string characterToScanFor = "e";
var stringToCheckAsCharacterArray = sentenceToScan.ToCharArray();
var characterToCheckFor = Char.Parse(characterToScanFor);
int numberOfOccurenes = stringToCheckAsCharacterArray.Count(n =>
n == characterToCheckFor);
Answer: 2
Count doesn't have a query expression syntax, it can only be appended at the end of a query expression like:
var count = (from t in stringToCheckAsCharacterArray
where t == characterToCheckFor).Count();
Or
var count = (from t in stringToCheckAsCharacterArray
where t == characterToCheckFor
select t).Count();
Personally I like Method expression, also LINQ query expression compiles in Method expressions. Your own code for Count with predicate is more readable IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With