好的,所以标题不是最好的.但这是我的问题:
我做了一个小程序,当一个外部程序发生某些事件时,会向.txt文件写一些名字和一个整数.
问题是文档中的名称可以显示在几行中,因此我想为每个特定的人提供整数,以便我获得他/她的总分数然后对其进行排序.
例如:
原线:
Aaaa Aaa 5 Bbbb Bbb 7 Cccc Ccc 2 Aaaa Aaa 4 Cccc Ccc 4 Bbbb Bbb 1 dddd Ddd 1
我想要的输出:
1. Aaaa Aaa 9 2. Bbbb Bbb 8 3. Cccc Ccc 6 4. dddd Ddd 1
有没有办法在C#中做到这一点?
我试图读取文件中的每一行并搜索一个人的名字.但这并没有真正帮助,我不知道如何解决这个问题.
有什么建议?
解决方法
此Linq查询将所需结果作为IEnumerable< string>返回:
IEnumerable<string> lineGroups = File.ReadLines(path) .Select((l,i) => new { Line = l,Parts = l.Split() }) .Select(x => new { Number = x.Parts.ElementAtOrDefault(2).TryGetInt() ?? 1,Col1 = x.Parts.ElementAtOrDefault(0),Col2 = x.Parts.ElementAtOrDefault(1),x.Line,x.Parts }) .GroupBy(x =>new { x.Col1,x.Col2 }) .Select((g,groupIndex) => string.Format("{0}. {1} {2} {3}",groupIndex + 1,g.Key.Col1,g.Key.Col2,g.Sum(x => x.Number)));
输出:
foreach (var grp in lineGroups) Console.WriteLine(grp);
这是输出:
1. Aaaa Aaa 9 2. Bbbb Bbb 8 3. Cccc Ccc 2 // different than your desired ouput but seems to be correct 4. dddd Ddd 1
这些是我在Linq查询中使用的扩展方法,尝试将字符串解析为常见值类型,如int(如上所述).如果它不可解析,则返回可空类型:
public static class NumericExtensions { public static bool IsBetween(this int value,int fromInclusive,int toInclusive) { return value >= fromInclusive && value <= toInclusive; } public static Decimal? TryGetDecimal(this string item) { Decimal d; bool success = Decimal.TryParse(item,out d); return success ? (Decimal?)d : (Decimal?)null; } public static int? TryGetInt(this string item) { int i; bool success = int.TryParse(item,out i); return success ? (int?)i : (int?)null; } public static bool TryGetBool(this string item) { bool b = false; Boolean.TryParse(item,out b); return b; ; } public static Version TryGetVersion(this string item) { Version v; bool success = Version.TryParse(item,out v); return v; } }