我需要一些帮助。基本上,我在文本文件中有一段文本,我需要将文本文件(存储为字符串)读入字符列表并存储它们在字符串中出现的时间。因此,它将在(A-Z)之间生成一个列表,并根据字符出现的次数对其进行排序。有没有办法在不使用LINQ的情况下执行此操作。
谢谢:)
答案 0 :(得分:3)
您可以使用哈希表来执行此操作。
Hashtable listofChars = new Hashtable();
for () { // your loop for the chars in the file
Char c ; // your char
if (!listofChars.ContainsKey(c))
{
listofChars[c] = 1;
}
else {
listofChars[c] = ((int)listofChars["c"]) + 1;
}
}
<强> - 编辑 - 强>
var listofChars = new SortedDictionary<char, int>();
foreach(char c in File.ReadAllText(fileName))
{
if (!listofChars.ContainsKey(c))
{
listofChars[c] = 1;
}
else
{
listofChars[c] += 1;
}
}
答案 1 :(得分:1)
一种有效且简单的方法是使用char作为键创建ConcurrentDictionary
,并将其显示为值。它有很好的AddOrUpdate(upsert)方法:
string text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
var chars = new System.Collections.Concurrent.ConcurrentDictionary<char, int>();
foreach (char c in text)
{
chars.AddOrUpdate(c, 1, (chr, count) => count + 1);
}
如果您想通过没有Linq(Lambda!= Linq)的号码订购,您可以使用以下代码:
List<KeyValuePair<char, int>> charList = chars.ToList();
charList.Sort((firstPair, nextPair) =>
{
return firstPair.Value.CompareTo(nextPair.Value);
});
修改:如果您想要将降序变更一点:
charList.Sort((firstPair, nextPair) =>
{
return -(firstPair.Value.CompareTo(nextPair.Value));
});
结果:
Console.Write(string.Join(Environment.NewLine, charList.Select(kv => string.Format("Char={0} Num={1}", kv.Key, kv.Value))));
Char= Num=90
Char=e Num=59
Char=t Num=43
Char=s Num=39
Char=n Num=38
Char=i Num=32
Char=a Num=28
Char=o Num=25
Char=r Num=24
Char=p Num=18
Char=m Num=18
Char=l Num=17
Char=u Num=17
Char=d Num=16
Char=h Num=14
Char=y Num=13
Char=g Num=11
Char=c Num=10
Char=k Num=7
Char=w Num=6
Char=f Num=6
Char=I Num=6
Char=v Num=5
Char=b Num=5
Char=L Num=5
Char=, Num=4
Char=. Num=4
Char=0 Num=3
Char=x Num=2
Char=1 Num=2
Char=' Num=1
Char=5 Num=1
Char=M Num=1
Char=A Num=1
Char=P Num=1
Char=6 Num=1
Char=9 Num=1