C#字符串数组中出现次数最少的元素

有一个字符串数组,有什么简单办法可以找到字符串数组中出现次数最少的元素,并找到它的位置

以下是基于LINQ的实现方案:

static void Main(string[] args)
{
    var list = new List<string> { "a", "b", "c", "e", "a", "b", "c", "a", "b", "d", "d", "d" };
    var occurrences = list.GroupBy(x => x)
        .Select(x => new
        {
            Group = x.Key,
            Count = x.Count()
        }).ToList();
    foreach (var occurrence in occurrences)
    {
        Console.WriteLine($"{occurrence.Group}出现{occurrence.Count}次");
    }
    var least = occurrences.OrderBy(x => x.Count).FirstOrDefault();
    Console.WriteLine($"出现最少次数的是:{least.Group}为{least.Count}次");
    var index = list
        .Select((x, i) => new { character = x, index = i })
        .Where(x => x.character == least.Group)
        .Select(x => x.index)
        .ToList();
    Console.WriteLine($"出现的索引位置分别为:{string.Join(",", index)}");
    Console.ReadKey();
}

运行结果:

a出现3b出现3次
c出现2次
e出现1次
d出现3次
出现最少次数的是:e为1次
出现的索引位置分别为:3