简体   繁体   English

合并并将两个列表绑定到gridview

[英]Merge and bind two lists to a gridview

I have two list of different objects : 我有两个不同的对象列表:

List<Report>
List<Newsletter>

each having a 'created date' property. 每个都具有“创建日期”属性。 I need to sort the created date of both lists in descending order and bind it to a gridview. 我需要按降序对两个列表的创建日期进行排序,并将其绑定到gridview。

How can this be done, as i can provide only one datasource? 我只能提供一个数据源,该怎么办?

You could firstly create List of dates: 您可以首先创建日期List

var rows = reports.Select(x => x.CreateDate).Union(news.Select(x => x.CreateDate)).OrderByDescending(x => x.Date).ToList();

And then use a DataTable structure for binding: 然后使用DataTable结构进行绑定:

DataTable dt = new DataTable();
dt.Columns.Add("Date");

foreach (var row in rows) {
   dt.Rows.Add(row);
}
grid.DataSource = dt;

If both types have the same properties you want displayed, then you could create an interface that they both implement. 如果两种类型都具有要显示的相同属性,则可以创建它们都实现的接口。 Then your view can have the following. 然后,您的视图可以具有以下内容。

PseudoCode: 伪代码:

List<IDisplayReportsAndNewsletter> data = new List<IDisplayReportsAndNewsletter>();

data.Addrange(reports);

data.Addrange(newsletters);

grid.Datasource = data.OrderBy(d => d.CreatedDate).ToList();

where reports and newsletters are the lists you describe above where the classes now implement your new IDisplayReportsAndNewsletter interface. 报告和新闻通讯是您在上面描述的列表,这些类现在实现了新的IDisplayReportsAndNewsletter接口。

The main benefit you get from this over the dataset option (which is also valid) is that you can still work with your domain objects in the view as opposed to having to translate to and from dataset rows. 通过数据集选项(这也是有效的),您从中获得的主要好处是,您仍然可以在视图中使用域对象,而不必在数据集行之间来回转换。

The downside is that you pollute your domain objects with an interface just for the purpose of your view 缺点是您仅出于查看目的而使用接口来污染域对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM