这是我的代码:
void Main() {
List<Restaurant> RestaurantData = new List<Restaurant>();
}
class Restaurant {
public int Id;
public List<Complaint> Complaints = new List<Complaints>();
}
class Complaint {
public string Name;
public string Address;
public int Age;
public DateTime ComplaintDate;
}
我想在 DataGridView 控件中显示 RestaurantData 中包含的数据。首先,我想显示餐厅的 ID,然后显示针对餐厅的投诉数量,使其看起来像这样(其中 ID 位于 A 列,名称位于 B 列,依此类推):
ID1, Name, Address, Age, Date (space), Name, Address, Age, Date (space), Name, Address, Age, Date ID2, Name, Address, Age, Date (space), Name, Address, Age, Date (space), Name, Address, Age, Date
Every restaurant has at least 1 complaint, and some restaurants may have many complaints. But in all cases, I want the Restaurant's ID to show up only once (with its complaints to follow). 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 = (from r in RestaurantData
from c in RestaurantData.Complaint
select new {Id = r.Id, Address =c.Address, Age = c.Age, Name = c.Name, Date = c.ComplaintDate}
).ToList();
dataGridView1.DataSource = ds;
目前,这会用相应的餐厅 ID 填充每一行。如何调整上述查询,使餐厅 ID 只显示一次?
最佳答案
你几乎就到了。您几乎已经得到了您想要的东西,并且正在适当的庄园中得到它,但您真正需要知道的是特定的投诉是否是该列表中的第一项。实现这一点的方法是在从具有索引作为参数的 complaints
中进行选择时使用 Select
的重载。为此,您需要使用方法语法,而不是查询语法,以便实现大部分更改。
一旦你有了索引,调整ID
就是一个非常简单的检查。
var data = restaurantData.SelectMany(restaurant =>
restaurant.Complaints.Select((complaint, index) => new
{
ID = index == 0 ? restaurant.Id.ToString() : "",
complaint.Name,
complaint.Address,
complaint.Age,
Date = complaint.ComplaintDate,
}));
关于c# - 如何在 C# 中显示对象的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19140953/