0

有问题的文件可以有一个或多个块,每个块以 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
4

2 回答 2

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);
    }
}
于 2013-06-20T09:30:45.133 回答
0

所以..你真的应该做一些艾哈迈德展示的事情。

尽管如此,你可以只使用 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

于 2013-06-20T10:26:21.897 回答