How merge two lists of different objects?

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

One solution

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());

Where A and B are some classes as follows

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

Another Solution

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());

Where A and B are having class definition as

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

If you just want a single List<object> containing all objects from both lists, that's fairly simple:

List<object> objectList = seminarList.Cast<object>()
    .Concat(conferenceList)
    .ToList();

If that's not what you want, then you'll need to define what you mean by "merge".

Tags:

C#

Linq