Reputation: 4434
Here is my code:
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>();
}
I'd like to present the data contained in RestaurantData in the DataGridView control. First, I'd like to show the Restaurant's ID, followed by the number of times it has been visited by the Dept. of Health (DOHVisits), then by the number of complaints (QtyComplaints), and finally by Complaint details if there are any. It would look something like this (where the ID is in column A, DOHVisits in Column B, and so forth):
Every restaurant will have at least 1 DOHVisit. Some restaurants have 0 complaints and some have many. But in all cases, I want the Restaurant's ID to show up only once (with its complaints to follow if they have any). My past usage of DataGridView has been limited to dataGridView1.DataSource = (some array). However, the information I want to present this time is clearly not an array so I'm stuck.
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;
The problem with the above code is that it leaves out all restaurants with 0 complaints. I'd like to include restaurant with zero complaints and have them show up in the datagrid.
Upvotes: 0
Views: 76
Reputation: 1288
First, I declare the class that implements each data row of the 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; }
}
The query can be written:
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
})));
Upvotes: 1