Piotrek
Piotrek

Reputation: 11221

How to store and sort two types of classes in List<>?

I have two classes:

public class SavedQuote
{
    public int ID { get; set; }
    public string Text { get; set; }
    public string Context { get; set; }
    public string URL { get; set; }
    public string Comment { get; set; }
    public string WhereToSearch { get; set; }

    public DateTime DateOfAdding { get; set; }

    public string OwnerName { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class NoteOnSite
{
    public int ID { get; set; }
    public string URL { get; set; }
    public DateTime DateOfAdding { get; set; }
    public string OwnerName { get; set; }
    public string Comment { get; set; }

    public virtual ICollection<Tag> Tags { get; set; }
}

I have also two lists: one that represents some "SavedQuotes" and one that has some "NoteOnSites". I need to sort data from those Lists by DateOfAdding and display them in one table on my webiste.

The problem is: I (probably) can't save objects with two different classes in one List<> (I need to do this to sort those objects). What do you advise me to do? How would you solve this problem?

Upvotes: 0

Views: 134

Answers (2)

jdweng
jdweng

Reputation: 34429

Try a little Linq using JOIN

            List<SavedQuote> savedQuotes = new List<SavedQuote>();
            List<NoteOnSite> noteOnSites = new List<NoteOnSite>();

            var results = from savedQuote in savedQuotes.OrderBy(x => x.DateOfAdding)
                          join noteOnSite in noteOnSites.OrderBy(x => x.DateOfAdding)
                          on savedQuote.ID equals noteOnSite.ID
                          select new { saved = savedQuotes, note = noteOnSites };​

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

I (probably) can't save objects with two different classes in one List<>

You can, as long as object have a common base class. In C#, all objects have a common base class System.Object, which is enough to store objects of entirely different types in a single list.

A heavyweight approach would be to put a common interface on the objects that you wish to sort:

public interface IWithDate {
    public DateTime DateOfAdding { get; set; }
}
public class SavedQuote : IWithDate {
    ...
}
public class NoteOnSite : IWithDate {
    ...
}
...
var mixedList = new List<IWithDate>();

However, this may introduce more structure than you wish: making the classes related to each other through a common interface is too much, if all you need is to sort objects of these classes together.

If you wish to sort the objects on a commonly named property without adding any static structure around your classes, you can make a list of dynamic objects, and use DateOfAdding directly:

var mixedList = new List<dynamic>();
mixedList.AddRange(quotes);
mixedList.AddRange(notes);
mixedList.Sort((a, b)=>a.DateOfAdding.CompareTo(b.DateOfAdding));

Upvotes: 2

Related Questions