Search code examples
c#stringcomparison

String comparison with foreach loop. The expected output is "Facebook"


How can we compare two elements in a string and display the most repeated value using the foreach loop?

class Program
{
    static void Main(string[] args)
    {
        string[] values = { "Facebook", "Google", "Facebook" };
        foreach (var value in values)
        {
            // need to comparing the elements in the array 
            Console.WriteLine(value); /* print the repeated value*/
        }            
    }
}

Solution

  • You could do this pretty easily with LINQ

    var mostRepeatedValue = values
                              .GroupBy(v => v)
                              .OrderByDescending(gp => gp.Count())
                              .Select(g => g.Key).FirstOrDefault();