2013-06-20 62 views
0

有問題的文件可以有一個或多個塊,每個塊以Processname:; ABC購買開頭。如何根據出現的字符串將文件內容分組爲塊

什麼是使用Linq將文件內容分割成塊的最佳方法是基於「過程名:; ABC購買」行的出現。

這似乎並不正常工作......

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

簡單和容易:

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); 
    } 
} 
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

相關問題