Shafeek Shafeek - 3 months ago 17
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.
(ie

List<class_A> X
&
List<class_B> Y
).

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

I need to sort these lists according to the
date
field.

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

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>()
                             .Concat(listB.Cast<ICommon>())
                             .OrderBy(q => q.DT)
    foreach (var obj in orderedResult)
        obj.Print();
}