Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How merge two lists of different objects?

Tags:

c#

linq

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
}

I have a list of:

List<Seminar>
List<Conference>

I need to merge them into a super List:

List<Object>

A code snippet would be great help.

like image 942
user3410713 Avatar asked Jul 04 '14 18:07

user3410713


2 Answers

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".

like image 160
Richard Deeming Avatar answered Sep 20 '22 11:09

Richard Deeming


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; }
}
like image 28
Durgesh Chaudhary Avatar answered Sep 20 '22 11:09

Durgesh Chaudhary