C.J.
C.J.

Reputation: 3527

How to find the most occurrence of a string within a List of string?

Example input:

List<string> input = new List<string>();
input.Add("\nHello \nWorld");
input.Add("My \nname \nis \John");
input.Add("\n\n\n\n Just for fun \n\n");

Targeted string: "\n"

Expected output: "\n\n\n\n Just for fun \n\n has the most "\n" and the number of occurrence is 6"

Notes:

  1. Search string is case insensitive, \n and \N should be considered as 2 occurrences.
  2. The user will enter the string to look for. \n is just an example. With the example above, if the user enters "m", the expected output would be My \nname \nis \John with 2 occurrences

Upvotes: 1

Views: 85

Answers (1)

Habib
Habib

Reputation: 223187

You can use:

var MaxIndex =  input.Select((r, i) => 
                new 
                { 

                  OccuranceCount = r.Count(c =>  char.ToUpperInvariant(c) == char.ToUpperInvariant(searchChar)),                         
                  Index = i 
                })
             .OrderByDescending(t => t.OccuranceCount)
             .FirstOrDefault();

So for the following code:

List<string> input = new List<string>();
input.Add("\nHello \nWorld");
input.Add("My \nname \nis John");
input.Add("\n\n\n\n Just for fun \n\n");

char searchChar = '\n';

var MaxIndex =  input.Select((r, i) => 
                new 
                { 

                  OccuranceCount = r.Count(c =>  char.ToUpperInvariant(c) == char.ToUpperInvariant(searchChar)),                         
                  Index = i 
                })
             .OrderByDescending(t => t.OccuranceCount)
             .FirstOrDefault();

Console.WriteLine("Line: {0}, Occurance Count: {1}", input[MaxIndex.Index], MaxIndex.OccuranceCount);

Upvotes: 1

Related Questions