使用 foreach 循环进行字符串比较。预期输出为 "Facebook"

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

我们如何比较字符串中的两个元素并使用 foreach 循环显示重复次数最多的值?

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*/
        }            
    }
}

您可以使用 LINQ 轻松做到这一点

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

你可以试试下面的代码

Dictionary<string, int> stringOccurDict = new Dictionary<string, int>();
string[] values = { "Facebook", "Google", "Facebook" };
foreach(string x in values)
{
     if (!stringOccurDict .ContainsKey(x))
          stringOccur.Add(x, values.Count(c => values.Contains(c)));
});
string repeatedString = stringOccur.Where(x => x.Value == stringOccur.Values.Max()).FirstOrDefault().Key;

输出

Facebook

您还可以使用 .Value

获取计数