在原始 A 和 B 类型不兼容且不可更改的情况下(可能它们来自某些类型不相关的数据库),您还可以使用使用 LINQ 的投影来合并它们。从本质上讲,这创建了第三类,尽管是匿名的。通常,当您可以修改类并使用基类或接口方法时,您应该避免这种方法,但是,由于这并不总是可行,下面是使用 LINQ 投影的示例。请注意,此示例中的原始类型具有不同的日期时间名称,可以在投影期间“合并”。
class Program
{
static void Main(string[] args)
{
List<A> aList = new List<A> {new A {OtherAData = "First A", SomeDateTime = DateTime.Parse("12-11-1980")},
new A {OtherAData = "Second A", SomeDateTime = DateTime.Parse("12-11-2000")} };
List<B> bList = new List<B> {new B {OtherBData = "First B", SomeOtherDateTime = DateTime.Parse("12-11-1990")},
new B {OtherBData = "Second B", SomeOtherDateTime = DateTime.Parse("12-11-2010")} };
// create projections
var unionableA = from a in aList
select new {SortDateTime = a.SomeDateTime, AValue = a, BValue = (B) null};
var unionableB = from b in bList
select new {SortDateTime = b.SomeOtherDateTime, AValue = (A) null, BValue = b};
// union the two projections and sort
var union = unionableA.Union(unionableB).OrderBy(u => u.SortDateTime);
foreach (var u in union)
{
if (u.AValue != null)
{
Console.WriteLine("A: {0}",u.AValue);
}
else if (u.BValue != null)
{
Console.WriteLine("B: {0}",u.BValue);
}
}
}
}
public class A
{
public DateTime SomeDateTime { get; set; }
public string OtherAData { get; set; }
public override string ToString()
{
return string.Format("SomeDateTime: {0}, OtherAData: {1}", SomeDateTime, OtherAData);
}
}
public class B
{
public DateTime SomeOtherDateTime { get; set; }
public string OtherBData { get; set; }
public override string ToString()
{
return string.Format("SomeOtherDateTime: {0}, OtherBData: {1}", SomeOtherDateTime, OtherBData);
}
}
样本输出:
A: SomeDateTime: 12/11/1980 12:00:00 AM, OtherAData: First A
B: SomeOtherDateTime: 12/11/1990 12:00:00 AM, OtherBData: First B
A: SomeDateTime: 12/11/2000 12:00:00 AM, OtherAData: Second A
B: SomeOtherDateTime: 12/11/2010 12:00:00 AM, OtherBData: Second B