微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何读取多行到同一行?

好的,所以标题不是最好的.但这是我的问题:

我做了一个小程序,当一个外部程序发生某些事件时,会向.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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐