我有一个 .csv 文件。 Column1, column2, column3
定义组合键。
Row column1 column2 column3
1 A 120 Hdr
2 A 120 Line
3 A 120 Line
4 B 130 Hdr
只要组合键重复,重复的行应如下所示:
3 A 120/1 Line
如果再次重复,对于即将到来的行,应将/1
递增到/2
,/3
,依此类推。我应该如何使用C#实现这一目标?
答案 0 :(得分:2)
如果您提供的是简单 CSV(没有引号),则可以尝试GroupBy
:
// Csv separator; it seems that you use `\t`
char sep = '\t';
var result = File
.ReadLines(@"c:\MyFile.csv")
//.Skip(1) // if you want to get rid of columns' captions
.Select(line => line.Split(new char[] {sep},
StringSplitOptions.RemoveEmptyEntries))
.GroupBy(items => new {
key1 = items[1],
key2 = items[2],
key3 = items[3], })
.SelectMany(chunk => chunk
.Select((items, index) => index == 0
? string.Join(sep.ToString(), items)
: string.Join(sep.ToString(),
items[0],
items[1],
$"{items[2]}/{index}",
string.Join(sep.ToString(), items.Skip(3)))));
演示:让我们以string text
进行测试:
string text =
@"1 A 120 Hdr
2 A 120 Line
3 A 120 Line
4 B 130 Hdr ";
我们将File.ReadLines
分成几行,而不是text
:
char sep = ' ';
var result = text
.Split(new char[] { '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Split(new char[] {sep},
StringSplitOptions.RemoveEmptyEntries))
.GroupBy(items => new {
key1 = items[1],
key2 = items[2],
key3 = items[3], })
.SelectMany(chunk => chunk
.Select((items, index) => index == 0
? string.Join(sep.ToString(), items)
: string.Join(sep.ToString(),
items[0],
items[1],
$"{items[2]}/{index}",
string.Join(sep.ToString(), items.Skip(3)))));
Console.Write(string.Join(Environment.NewLine, result));
结果:
1 A 120 Hdr
2 A 120 Line
3 A 120/1 Line
4 B 130 Hdr