Shafeek Shafeek - 1 year ago 87
C# Question

How to combine two types of C# lists into one?

I have created two lists say X & Y. These two lists are of different types.

List<class_A> X
List<class_B> Y

Values in both these lists are different. But there is a
field in both these lists.

I need to sort these lists according to the

I have separate functions to print the details of list A and List B.

Suppose the sorted list looks like

  • tuple from list A,

  • tuple from list B,

  • tuple from list A,

  • tuple from list B,

My purpose is to loop through this list and call the appropriate function to display the details. ie if the tuple is from list A then call the function for printing list A's details and vice versa.

Answer Source

You can create an interface to host your common properties and functions, then join those lists after casting to this interface and sort it then:

interface ICommon
    DateTime DT { get; }
    void Print();
class ClassA : ICommon
    public DateTime DT { get; set; }
    public void Print() { Console.WriteLine("A " + DT); }
class ClassB : ICommon
    public DateTime DT { get; set; }
    public void Print() { Console.WriteLine("B " + DT); }

public static void Main()
    var listA = new List<ClassA> { new ClassA() { DT = DateTime.Now.AddDays(-1) }, new ClassA() { DT = DateTime.Now.AddDays(-3) }};
    var listB = new List<ClassB> { new ClassB() { DT = DateTime.Now.AddDays(-2) }, new ClassB() { DT = DateTime.Now.AddDays(-4) }};

    var orderedResult = listA.Cast<ICommon>()
                             .OrderBy(q => q.DT)
    foreach (var obj in orderedResult)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download