如何根据字符串的出现情况将文件内容分组为块
本文关键字:文件 情况 何根 字符串 | 更新日期: 2023-09-27 18:19:15
所讨论的文件可以有一个或多个块,每个块以Processname:;ABC purchasing开头。
使用Linq将文件内容分成基于"Processname:;"这一行的块的最好方法是什么?美国广播公司购买"。
这似乎不能正常工作…
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
简单明了:
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);
}
}
所以…你真的应该像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