此 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 查询中使用的扩展方法,用于尝试解析一个string
常见的值类型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;
}
}