我将保持数据库原样并在您的应用程序中运行报表操作,类似于我在下面所做的操作,使用 Northwind 数据库并将客户加入订单,订单 ID 代替您的注册号。
创建两个类:
public class Customer
{
public string Name { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
}
为您的数据创建一个数据集,其中包含客户和订单的数据表以及外键上的表之间的关系。我使用了一个类型化的数据集来自动创建适配器,但如果你手动滚动,同样的原则也适用。
创建一个 ViewModel 类来获取数据并对其进行排列。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SO_StringAggregate
{
public class ViewModel
{
public ViewModel()
{
// populate the data set
var dataSet = new NorthwindDataSet();
using (var customersAdp = new NorthwindDataSetTableAdapters.CustomersTableAdapter())
using (var ordersAdp = new NorthwindDataSetTableAdapters.OrdersTableAdapter())
{
customersAdp.Fill(dataSet.Customers);
ordersAdp.Fill(dataSet.Orders);
}
// populate your domain objects
var customers = dataSet.Customers.ToArray().Select(cust => new Customer
{
Name = cust.Company_Name,
Orders = cust.GetOrdersRows().Select(order => new Order { Id = order.Order_ID })
});
this.Customers = customers;
// build the report
StringBuilder report = new StringBuilder();
string formatString = "{0,-30}|{1}";
report.Append(string.Format(formatString, "Name", "Order Ids"));
report.Append(Environment.NewLine);
Customers.ToList().ForEach(cust => report.AppendLine(string.Format(
formatString,
cust.Name,
string.Join(",", cust.Orders.Select(o => o.Id).ToArray()))
));
// display the report
Report = report.ToString();
}
public IEnumerable<Customer> Customers { get; set; }
public string Report { get; set; }
}
}
然后,您可以在绑定到 Report 属性的视图中显示数据。
<Window x:Class="SO_StringAggregate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox FontFamily="Consolas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Text="{Binding Report}" />
</Grid>
</Window>