Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query Syntax (Count Operation)

Tags:

c#

linq

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
like image 909
Patrick Avatar asked Apr 21 '26 21:04

Patrick


1 Answers

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.

like image 133
Habib Avatar answered Apr 23 '26 10:04

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!