如何在List<>?中存储和排序两种类

时间:2015-05-31 10:40:34

标签: c#

我有两个班级:

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; }
}

我还有两个列表:一个代表一些“SavedQuotes”,一个代表一些“NoteOnSites”。我需要按DateOfAdding对这些列表中的数据进行排序,并将其显示在我的网站上的一个表中。

问题是:我(可能)无法在一个List<>中保存具有两个不同类的对象(我需要这样做以对这些对象进行排序)。你建议我做什么?你会如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

  

我(可能)不能在一个Txt[N] = (isupper(Txt[N]) ? tolower(Txt[N]) : toupper(Txt[N])); 中保存具有两个不同类的对象

只要对象具有公共基类,您就可以。在C#中,所有对象都有一个公共基类List<>,足以在一个列表中存储完全不同类型的对象。

重量级方法是在要排序的对象上放置一个公共接口:

System.Object

然而,这可能会引入比你想要的结构更多的结构:如果只需要将这些类的对象组合在一起,那么通过公共接口使彼此相关的类太多了。

如果您希望在通常命名的属性上对对象进行排序而不在类周围添加任何静态结构,则可以创建public interface IWithDate { public DateTime DateOfAdding { get; set; } } public class SavedQuote : IWithDate { ... } public class NoteOnSite : IWithDate { ... } ... var mixedList = new List<IWithDate>(); 个对象的列表,并直接使用dynamic

DateOfAdding

答案 1 :(得分:1)

使用JOIN尝试一点Linq

            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 };​