c# - 如何在 C# 中显示对象的数据?

标签 c# winforms data-binding datagridview

这是我的代码:

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/

相关文章:

c# - 如何重写 TreeNode.Clone() 方法?

.net - Windows 窗体的验证控件?

c# - 如何关闭表格

c# - 在 Entity Framework 中设置

c# - 学习 C#/.NET 是否需要订阅 MSDN?

c# - 列出/详细说明不同的窗口是否可以同步并数据绑定(bind)到同一个集合?

data-binding - Grails 数据绑定(bind)

c# - WPF 方形单元

c# - Entity Framework : read only property vs parameter-less method

c# - 长时间运行的进程的并行化和性能优化