使用Linq计算字符串中的字符时的重复输出

时间:2016-04-13 11:08:00

标签: c# string linq duplicates chars

我对此代码的输出有这个问题,它输出字符串中的字符被提及的次数。

Alabala
a => 4
a => 4
a => 4
a => 4
b => 1
l => 2
l => 2

这是我得到的输出:

Alabala
a => 4
b => 1
l => 2

这是我想要的输出

Sub test()

    Dim rngTarget As Range
    Set rngTarget = Sheet1.Range("A1")
    Set rngTarget = Range(rngTarget, rngTarget.End(xlDown))

    Dim rngIndex As Range

    For Each rngIndex In rngTarget
        With rngIndex
            .Value = .Value - 1
        End With
    Next rngIndex

End Sub

如果有人帮助我,我将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以在单个linq中执行此操作,如下所示:

string str =  Console.ReadLine().ToLower();
string sortedString = String.Concat(str.OrderBy(c => c));

var result = sortedString.GroupBy(x => x)
                         .Select(y => string.Format("{0} => {1}", y.Key, y.Count())).ToList();

foreach (var output in result)
{
    Console.WriteLine(output);
}

答案 1 :(得分:2)

您可以结合使用ToDictionary()OrderBy()Distinct()方法:

        string str = "halleluyah";

        var grouppedChars = str
            .Distinct()       // removes duplicates
            .OrderBy(c => c)  // orders them alphabetically
            .ToDictionary(    // converts to dictionary [string, int]
                c => c,
                c => str.Count(c2 => c2 == c));

        foreach (var group in grouppedChars)
        {
            Console.WriteLine($"{group.Key} => {group.Value}");
        }

        Console.ReadKey();

输出:

a => 2
e => 1
h => 2
l => 3
u => 1
y => 1

P.S。 这比GroupBy()更好,因为你真的不想将这些字符分组保存在某个地方,而只是保留它们的数量。

方法2,使用char信息添加自己的struct:

        struct CharStatistics
        {
           public readonly char @char;
           public readonly int count;

           public CharStatistics(char @char, int count)
           {
              this.@char = @char;
              this.count = count;
           }
        }

在主要方法中:

        string str = "halleluyah";

        var charsInfo = str
            .OrderBy(c => c)
            .Distinct()
            .Select(c =>
                new CharStatistics(c, str.Count(c2 => c2 == c)));

        foreach (var stats in charsInfo)
        {
            Console.WriteLine($"{stats.@char} => {stats.count}");
        }