Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two lists of different types and sort them by date

Tags:

c#

list

I have a first list of entities like this :

public partial class Networking :EntityBase
{

    public virtual int NetWorkingId
    {
        get;
        set;
    }

    public virtual string NetWorkingParam
    {
        get;
        set;
    }

    public virtual System.DateTime NetWorkingDate
    {
        get;
        set;
    }
}

And I have a second list of entities like this:

public partial class PrivateNetwork :EntityBase
{
    public virtual int PrivateNetworkId
    {
        get;
        set;
    }

    public virtual int ContaId
    {
        get { return _contaId; }
        set
        {
            if (_contaId != value)
            {
                if (Contact != null && Contact.ContaId != value)
                {
                    Contact = null;
                }
                _contaId = value;
            }
        }
    }

    public virtual Nullable<System.DateTime> DateCreation
    {
        get;
        set;
    }
}

I want to collect these two lists in one and sort all the elements by date.

Is that possible ?

like image 500
kbaccouche Avatar asked Nov 13 '12 08:11

kbaccouche


2 Answers

You can do this, although it's not very pretty, and you end up with an IEnumerable<object> so you have to check each item's type before you can use it:

IEnumerable<object> sorted = myNetworkingList
    .Concat<object>(myPrivateNetworkList)
    .OrderBy(n => n is Networking
                 ? (DateTime?)((Networking)n).NetWorkingDate
                 : ((PrivateNetwork)n).DateCreation);

foreach (object either in sorted)
{
    if (either is Networking)
        // Networking; do something
    else
        // PrivateNetwork; do something else
}
like image 137
Rawling Avatar answered Nov 02 '22 23:11

Rawling


This problem could easily be solved by using polymorphism; use a common base class or interface for both classes, which has the DateTime property you want to sort on.

Example:

public abstract class NetworkingBase : EntityBase
{
    public DateTime DateToSortOn { get; set; }
}

or

public interface INetworking
{
    public DateTime DateToSortOn { get; set; }
}

And then make your classes derive from NetworkingBase or implement INetworking:

public partial class Networking : NetworkingBase
{
    ...
}

public partial class PrivateNetwork : NetworkingBase
{
    ...
}

or

public partial class Networking : EntityBase, INetworking
{
    ...
}

public partial class PrivateNetwork : EntityBase, INetworking
{
    ...
}

Do a LINQ Union or Concat and then an OrderBy on the resulting collection.

like image 26
khellang Avatar answered Nov 02 '22 22:11

khellang