如何根据字符串的出现将文件内容分组为块

时间:2013-06-20 09:24:24

标签: c# .net linq

有问题的文件可以有一个或多个块,每个块以Processname :; ABC Buying开头。

使用Linq根据“Processname:; ABC Buying”行的出现将文件内容拆分为块的最佳方法是什么?

这似乎无法正常工作......

var lines = File.ReadAllLines(path).OfType<string>().ToList();
var grps = lines.GroupBy(blocks => blocks.Contains("Processname:;ABC Buying"));

文件

Processname:;ABC Buying
ID:;31
Message Date:;08-02-2012

Receiver (code):;12345
Object code:


Location (code):;12345
Date;time
2012.02.08;00:00;0;0,00
2012.02.08;00:15;0;0,00
2012.02.08;00:30;0;0,00
2012.02.08;00:45;0;0,00
2012.02.08;01:00;0;0,00
2012.02.08;01:15;0;0,00
Processname:;ABC Buying
ID:;41
Message Date:;08-02-2012

Receiver (code):;12345
Object code:


Location (code):;12345
Date;time
2012.02.08;00:00;0;17,00
2012.02.08;00:15;0;1,00
2012.02.08;00:30;0;15,00
2012.02.08;00:45;0;0,00
2012.02.08;01:00;0;0,00
2012.02.08;01:15;0;9,00

2 个答案:

答案 0 :(得分:2)

简单易行:

var lines = File.ReadLines(path);
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach(var line in lines){
    if (line.Contains("Processname:;ABC Buying")){
        current = new List<string>();
        groups.Add(current);
    }
    else if (current != null) {
        current.Add(line);
    }
}

答案 1 :(得分:0)

所以......你应该像Ahmed所展示的那样做。

尽管如此,你可以只使用Linq做这样的(不是非常有效的)代码:

var lines = new[] { "wierd", "a1", "b1", "b2", "b3", "a2", "b4", "a3", "b5", "b6" };
List<List<string>> groups = lines
    .Select((x, i) => Tuple.Create(x, x.StartsWith("a") ? new int?(i) : null))
    .Aggregate(Tuple.Create<IEnumerable<Tuple<string, int>>, Nullable<int>>(Enumerable.Empty<Tuple<string, int>>(), null), 
        (acc, x) => x.Item2.HasValue
            ? Tuple.Create(acc.Item1.Concat(new[] { Tuple.Create(x.Item1, x.Item2 ?? -1) }), x.Item2)
            : Tuple.Create(acc.Item1.Concat(new[] { Tuple.Create(x.Item1, acc.Item2 ?? -1) }), acc.Item2))
    .Item1
    .GroupBy(x => x.Item2)
    .Select(x => x.Select(y => y.Item1).ToList())
    .ToList();

foreach(var group in groups) 
{
    Console.WriteLine("--New group--");
    foreach (var line in group)
    {
        Console.WriteLine(line);
    }
}

在此测试:https://compilify.net/2tr