如何合并两个不同对象的列表?

问题描述:

使用C#和LINQ,如何合并两个不同对象列表,例如Seminar和Conference? 它们具有一些公共的和一些不同的字段/属性,并且不共享唯一的ID.

Using C# with LINQ, how can I merge two lists of different objects, say, Seminar and Conference? They have some common and some different fields/properties and do not share unique id.

class Seminar
{
   int id,
   DateTime joinDate,
   string name
}

class Conference
{
   Guid confNumber,
   DateTime joinDate
   Type type
}

我有一个清单:

List<Seminar>
List<Conference>

我需要将它们合并为超级List:

I need to merge them into a super List:

List<Object>

代码段会很有帮助.

如果这是您对合并"的定义,则下面的代码对我来说很好用

Following code works fine for me, if this is your definition of Merge

一种解决方案

List<A> someAs = new List<A>() { new A(), new A() };
List<B> someBs = new List<B>() { new B(), new B { something = new A() } };

List<Object> allS = (from x in someAs select (Object)x).ToList();
allS.AddRange((from x in someBs select (Object)x).ToList());

其中A和B是一些类,

class A
{
    public string someAnotherThing { get; set; }
}
class B
{
    public A something { get; set; }
}

另一种解决方案

List<A> someAs = new List<A>() { new A(), new A() };
List<B> someBs = new List<B>() { new B(), new B { something = string.Empty } };

List<Object> allS = (from x in someAs select (Object)new { someAnotherThing = x.someAnotherThing, something = string.Empty }).ToList();
allS.AddRange((from x in someBs select (Object)new { someAnotherThing = string.Empty, something = x.something}).ToList());

A和B的类定义为

class A
{
    public string someAnotherThing { get; set; }
}
class B
{
    public string something { get; set; }
}