c# – 如何读取多行到同一行?
发布时间:2020-12-16 00:08:07 所属栏目:百科 来源:网络整理
导读:好的,所以标题不是最好的.但这是我的问题: 我做了一个小程序,当一个外部程序发生某些事件时,会向.txt文件写一些名字和一个整数. 问题是文档中的名称可以显示在几行中,因此我想为每个特定的人提供整数,以便我获得他/她的总分数然后对其进行排序. 例如: 原线
好的,所以标题不是最好的.但这是我的问题:
我做了一个小程序,当一个外部程序发生某些事件时,会向.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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |