我读过一些听起来类似的文章,但我不太能理解其中讨论的内容。我使用的是c#实体框架代码和MVC 4。以下是一些模型的层次结构。
Project
ProjectImage
ProjectDoc
Comment
CommentVote
CommentReply
CommentReplyVote
所有这些模型都有一个DateCreated字段。我想运行一个查询,我可以按日期排序,并在同一列表中显示最新到最老的任何这些事件。我想以不同的方式处理(显示)每一个。我不知道从哪里开始,也不知道在Stackoverflow上使用什么搜索词来找到答案。
这是我承诺的代码…
它不是最先进的,但它是一个简单的控制台应用程序,让你知道如何处理这个问题。我基本上是从列表中读取(在您的例子中,您是从数据库表中读取)。然后,我将DateCreated
和对象本身添加到一个自定义类中,该类允许通过DateCreated
字段对所有对象进行排序。表示代码由您决定,但我将向您展示如何根据对象类型打印到控制台。
class Program
{
static void Main(string[] args)
{
var projects = new List<Project>{
new Project() { ProjectId = 1, ProjectName = "My Secret Project", DateCreated = DateTime.Today.AddHours(-1) },
new Project() { ProjectId = 2, ProjectName = "My Big Project", DateCreated = DateTime.Today.AddHours(-2) }};
var projectImages = new List<ProjectImage> {
new ProjectImage() { ProjectImageId = 1, ProjectImageSize = 17.17, DateCreated = DateTime.Today.AddHours(-3) },
new ProjectImage() { ProjectImageId = 2, ProjectImageSize = 10.17, DateCreated = DateTime.Today.AddHours(-4) }};
var objects = new List<MyCustomClass>();
foreach (var project in projects)
{
objects .Add(
new MyCustomClass() { DateCreated = project.DateCreated, Object = project });
}
foreach (var projectImage in projectImages)
{
objects.Add(
new MyCustomClass() { DateCreated = projectImage.DateCreated, Object = projectImage });
}
// Objects ordered by Date, Newest first...
var objectsByDateCreated = objects.OrderByDescending(o => o.DateCreated);
foreach (var @object in objectsByDateCreated)
{
Console.WriteLine(string.Format("{0} => {1}", @object.Object.GetType().Name, @object.DateCreated));
}
// Displaying objects according to type
foreach (var @object in objectsByDateCreated)
{
if (@object.Object is Project)
{
var project = @object.Object as Project;
Console.WriteLine(project.ProjectName);
}
else if (@object.Object is ProjectImage)
{
var projectImage = @object.Object as ProjectImage;
Console.WriteLine(projectImage.ProjectImageSize);
}
}
}
}
public class MyCustomClass
{
public DateTime DateCreated { get; set; }
public object Object { get; set; }
}
public class Project
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public DateTime DateCreated { get; set; }
}
public class ProjectImage
{
public int ProjectImageId { get; set; }
public double ProjectImageSize { get; set; }
public DateTime DateCreated { get; set; }
}