您可以使用Linq将两个数据源转换为相同类型,然后将它们合并并对它们进行排序。在这里,我有一个来自假装数据库表T_Log的对象,它具有Timestamp字段和其他一些字段,另一个来源是一些来自假文件的字符串,其中每个字符串包含行开头的时间戳。我将它们转换为自定义类CommonLog
,然后用它来排序。 CommonLog包含对原始对象的引用,所以如果我需要更详细的信息,我可以投射并获取该信息。
更轻量级的实现可以转换为已存在的类,如KeyValuePair<DateTime, object>
。
下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Fake database class.
class T_Log
{
public DateTime Timestamp { get; set; }
public string Info { get; set; }
public int Priority { get; set; }
}
static void Main(string[] args)
{
// Create some events in the fake database.
List<T_Log> dbLogs = new List<T_Log> {
new T_Log { Timestamp = new DateTime(2009, 2, 5), Info = "db: foo", Priority = 1 },
new T_Log { Timestamp = new DateTime(2009, 2, 9), Info = "db: bar", Priority = 2 }
};
// Create some lines in a fake file.
List<string> fileLogs = new List<string> {
"2009-02-06: File foo",
"2009-02-10: File bar"
};
var logFromDb =
dbLogs.Select(x => new CommonLog(
x.Timestamp,
string.Format("{1} [Priority={2}]",
x.Timestamp,
x.Info,
x.Priority),
x));
var logFromFile =
fileLogs.Select(x => new CommonLog(
DateTime.Parse(x.Substring(0, x.IndexOf(':'))),
x.Substring(x.IndexOf(':') + 2),
x
));
var combinedLog = logFromDb.Concat(logFromFile).OrderBy(x => x.Timestamp);
foreach (var logEntry in combinedLog)
Console.WriteLine("{0}: {1}", logEntry.Timestamp, logEntry.Log);
}
}
// This class is used to store logs from any source.
class CommonLog
{
public CommonLog(DateTime timestamp,
string log,
object original)
{
this.Timestamp = timestamp;
this.Log = log;
this.Original = original;
}
public DateTime Timestamp { get; private set; }
public string Log { get; private set; }
public object Original { get; private set; }
}
输出:
05-02-2009 00:00:00: db: foo [Priority=0]
06-02-2009 00:00:00: file: baz
09-02-2009 00:00:00: db: bar [Priority=0]
10-02-2009 00:00:00: file: quux
更新:马丁回答说在这条信息的评论下面,但由于缺乏在评论格式是很难读。这里是格式化:
var ld = rs.Select(x => new KeyValuePair<DateTime, object>(DateTime.Parse(x[0]), x))
.Concat(ta.Select(y => new KeyValuePair<DateTime, object>(y.Tidspunkt, y)))
.OrderBy(d => d.Key);
非常感谢很多人!现在,我不得不在这里挑一点,那里得到它的工作:) 作为我的第一个名单是名单与S中的时间戳[0] 第二个列表是一个表类的一个元素的日期时间 结合所有我结束了: var ld = rs.Select(x => new KeyValuePair (DateTime.Parse(x [0]),x)) .Concat(ta.Select(y => new KeyValuePair (y.Tidspunkt,y)))。OrderBy(d => d.Key); 而作为值类型是多态的: 的foreach(在LD VAR米) { 如果(m.Value是Nettbud) ... 其他 ... } 马丁 –
Martin
2009-12-11 08:33:04
感谢您让我们知道你怎么了。并且不要忘记接受答案。 :) – 2009-12-11 08:36:58
抱歉,这是我第一次来这里。看不到任何格式指南,扩大600chars和标记回答! Martin – Martin 2009-12-11 08:51:46