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

时间:2018-11-09 00:27:36

标签: c# list formatting

我有两个保存日志数据的列表(这些列表包含字符串)。
示例list1的外观如下(每个条目都是一个字符串):
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
list2示例的外观如下:
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

我的目标是拥有一个看起来如下所示的list3:
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”文件,并按特定特征分开,因此我最终不得不合并两个以上的列表,但是第一步是生成了我能够完成的列表。

2 个答案:

答案 0 :(得分:0)

您可以通过先获取时间然后再订购来使用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

如您在this fiddle中所见。

答案 1 :(得分:0)

如果排序每个列表,最有效的方法是进行合并(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++]); }