这是我承诺的代码...
它不是最先进的,但它是一个简单的控制台应用程序,可让您了解如何处理此问题。我基本上是从列表中读取的(在您的情况下,您将从数据库表中读取)。然后我将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; }
}