![](/img/trans.png)
[英]How can I get the largest, and smallest number from a list using LINQ, without using Min() Max()?
[英]How can I sort numbers from largest to smallest in this code block?
在打印输出中,数字将从大到小列出,字母将写在它们旁边。
Console.Write("Enter Sentence : ");
String sentence = Console.ReadLine();
Console.WriteLine("-----------------------------");
sentence = sentence.ToLower();
String characters = "0123456789abcdefghijklmnopqrstuvwxyz.?,;";
int[] count = new int[characters.Length];
for (int i = 0; i < sentence.Length; i++)
{
int index = characters.IndexOf(sentence[i]);
if (index < 0)
continue;
else
{
count[index]++;
}
}
for (int i = 0; i < count.Length; i++)
{
if (count[i] < 1)
continue;
else
{
Console.WriteLine(" " + characters[i] + " = " + count[i]);
}
Console.WriteLine("-----------------------------");
}
Console.ReadKey();
我会使用Dictionary<char, int>
来计算该句子中每个字符的出现次数。 这是最有效的方法。 然后你可以使用一个简单的单行 LINQ 按计数排序:
sentence = sentence.ToLower();
var charCounter = new Dictionary<char, int>(sentence.Length);
foreach(char c in sentence)
{
charCounter.TryGetValue(c, out int count);
charCounter[c] = ++count;
}
foreach(var kv in charCounter.OrderByDescending(kv => kv.Value))
{
Console.WriteLine($"{kv.Key} = {kv.Value}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.