I need to have the simple way to count the number of occurences of all elements of a list into that same list in C# I know this is possible and also used in many applications but I did not able to solve this problem.
I need to have the simple way to count the number of occurences of all elements of a list into that same list in C# I know this is possible and also used in many applications but I did not able to solve this problem.
In the Main method, which we use to test the CountStringOccurrences method, we see that "Sam" occurs twice in the example string, matching the requirement. There is a performance cost to the Split method. If the only operation on the string is to count the words, you should consider using the Matches or IndexOf methods instead.It is usually best to simplify the branches in your code, avoiding as many conditionals/ifs as possible. This loop only tests one condition, the result of IndexOf.
Try following example, and check if it works as per your requirement if yes then you may use your numbers to get the expected result i found this code on the internet.
Code:var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 }; var g = l1.GroupBy( i => i ); foreach( var grp in g ) { Console.WriteLine( "{0} {1}", grp.Key, grp.Count() ); }
In the above mentioned program outer loop of looping over all the words in the list is unnecessary and will cause problems to count the occurrence of a string. Remove the outer loop and it looks like what you have should work properly. However, if performance is not a critical issue, or you have already split the sentence in order to perform other types of queries over it, then it makes sense to use LINQ to count the words or phrases as well. following is the C++ code but this is very clear and easy to understand.
Code:public static int CountChar ( string input, char c ) { int retval = 0; for (int i = 0; i < input.Length; i ++) if (c == input [i]) retval ++; return retval; }
Bookmarks