<string> 使用列表中的时间戳合并两个列表



我有两个列表,其中包含日志记录数据(这些列表包含字符串(
示例列表1的外观如下(每个条目都是一个字符串(:
11:03:01:003 INFO some event has occurred 11:03:31:004 DEBUG another event has occurred 11:04:01:015 INFO third event has occurred
示例清单2的外观如下:
11:03:16:003 INFO fourth event has occurred 11:03:32:025 DEBUG fifth event has occurred 11:03:54:023 INFO sixth event has occurred

我的目标是有一个列表3,看起来如下:
11:03:01:003 INFO some event has occurred 11:03:16:003 INFO fourth event has occurred 11:03:31:004 DEBUG another event has occurred 11:03:32:025 DEBUG fifth event has occurred 11:03:54:023 INFO sixth event has occurred 11:04:01:015 INFO third event has occurred

我一直在想一种有效的方法来解决这个问题(因为日志文件可能会变得很重(,但我真的没能解决。

编辑:列表来自".txt"文件,并按特定特性进行拆分,因此我最终可能不得不合并两个以上的列表,但我必须做的第一步是生成我能够完成的列表。

您可以使用LINQ,首先获取时间,然后排序:

var result = list
.Select(x => 
{ 
return new { Log = x, Time = TimeSpan.Parse(x.Split(' ')[0]) }; 
})
.OrderBy(x => x.Time)
.Select(x => x.Log) // only if you don't care anymore about the time
.ToArray();

例如,类似这样的东西:

var list = new List<string>();
list.Add("11:03:01:003 INFO some event has occurred");
list.Add("11:03:31:004 DEBUG another event has occurred");
list.Add("11:04:01:015 INFO third event has occurred");
var list2 = new List<string>();
list2.Add("11:03:16:003 INFO fourth event has occurred");
list2.Add("11:03:32:025 DEBUG fifth event has occurred");
list2.Add("11:03:54:023 INFO sixth event has occurred");
var result = list
// Merge both lists
.Union(list2)
.Select(x => 
{ 
return new { Log = x, Time = TimeSpan.Parse(x.Split(' ')[0]) }; 
})
.OrderBy(x => x.Time)
.ToArray();
foreach (var log in result)
{
Console.WriteLine(log.Time + " => " + log.Log);
}

打印:

11.03:01:03 => 11:03:01:003 INFO some event has occurred
11.03:16:03 => 11:03:16:003 INFO fourth event has occurred
11.03:31:04 => 11:03:31:004 DEBUG another event has occurred
11.03:32:25 => 11:03:32:025 DEBUG fifth event has occurred
11.03:54:23 => 11:03:54:023 INFO sixth event has occurred
11.04:01:15 => 11:04:01:015 INFO third event has occurred

正如你在这把小提琴上看到的。

如果对每个列表进行排序,最有效的方法是进行合并(O(m + n),其中m和n是列表的长度(,就像在合并排序算法中一样:

var result = new List<string>(m+n);
int i = 0, j = 0;
while (i < l1.Count && j < l2.Count) {
if (l1[i] < l2[j]) { // Of course you have to change this part, the idea is to compare both items
result.Add(l1[i++]);
} else {
result.Add(l2[j++]);
}
}
while(i < l1.Count) { result.Add(l1[i++]); }
while(j < l2.Count) { result.Add(l2[j++]); }

最新更新