下面是我的代码:
public class Restaurant {
public int ID { get; set; }
public int DOHVisits { get; set; }
public int QtyComplaints { get; set; }
public List<Complaint> Complaints = new List<Complaint>();
}
public class Complaint {
public string Name; { get; set; }
public string Address; { get; set; }
public string Description; { get; set; }
public DateTime ComplaintDate; { get; set; }
}
void Main() {
List<Restaurant> RestaurantData = new List<Restaurant>();
}
我想在DataGridView控件中显示RestaurantData中包含的数据。首先,我想显示餐厅的ID,然后是卫生部访问的次数(dohvisited),然后是投诉的次数(QtyComplaints),最后是投诉的详细信息(如果有的话)。它看起来应该是这样的(其中ID在A列,dohvisited在B列,以此类推):
- ID, doh访问量,投诉量,姓名,地址,描述,投诉日期
- 1234、8、0、空白、空白、空白、空白
- 5678, 23,5,姓名,地址,描述,投诉日期
- (空格)、(空格)、(空格)、姓名、地址、描述、投诉日期
- (空格),(空格),(空格),姓名,地址,描述,ComplaintDate
- (空格),(空格),(空格),姓名,地址,描述,ComplaintDate
- (空格)、(空格)、(空格)、姓名、地址、描述、投诉日期
每个餐厅将至少有一个DOHVisit。有些餐馆没有投诉,有些则有很多。但在所有情况下,我都希望餐厅的ID只显示一次(如果有任何投诉,请在后面跟进)。我过去对DataGridView的使用仅限于dataGridView1。数据源=(某个数组)。然而,这次我想要呈现的信息显然不是一个数组,所以我卡住了。
var ds = RestaurantData.OrderByDescending(x => x.DOHVisits).SelectMany(Restaurant
=> Restaurant.Complaint.Select((Complaint, index)
=> new
{
ID = index >= 0 ? Restaurant.ID.ToString() : "",
DOHVisits = Restaurant.DOHVisits.ToString(),
QtyComplaints = Restaurant.QtyComplaints.ToString(),
Complaint.Name,
Complaint.Address,
Complaint.Description,
Complaint.ComplaintDate
})).ToList();
dataGridView1 = ds;
上面代码的问题是它忽略了所有投诉为0的餐厅。我想包括零投诉的餐厅,并让它们出现在数据网格中。
首先,我声明实现GridView的每个数据行的类:
class ResultLine
{
public int? ID { get; set; }
public int? DOHVisits { get; set; }
public int? QtyComplaints { get; set; }
public string ComplaintName { get; set; }
public string ComplaintAddress { get; set; }
public string ComplaintDescription { get; set; }
public DateTime? ComplaintDate { get; set; }
}
可以这样写:
IEnumerable<ResultLine> lines = RestaurantData.OrderByDescending(x => x.DOHVisits)
.SelectMany(r => new List<ResultLine>() {
new ResultLine() {
ID = r.ID,
DOHVisits = r.DOHVisits,
QtyComplaints = r.QtyComplaints,
ComplaintName = null,
ComplaintAddress = null,
ComplaintDescription = null,
ComplaintDate = null
}
}.Concat(r.Complaints.OrderBy(c => c.ComplaintDate).Select(c => new ResultLine() {
ID = null,
DOHVisits = null,
QtyComplaints = null,
ComplaintName = c.Name,
ComplaintAddress = c.Address,
ComplaintDescription = c.Description,
ComplaintDate = c.ComplaintDate
})));