加入多个数据行到一个单一的DataRow [英] Join multiple DataRows into a single DataRow

查看:259
本文介绍了加入多个数据行到一个单一的DataRow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.NET 3.5编写这在C#。我有一个使用以下架构一个DataTable将System.Data.DataSet对象:

I am writing this in C# using .NET 3.5. I have a System.Data.DataSet object with a single DataTable that uses the following schema:

Id      :  uint
AddressA:  string
AddressB:  string
Bytes   :  uint

当我跑我的应用程序,让我们说DataTable中被填充了以下内容:

When I run my application, let's say the DataTable gets filled with the following:

1   192.168.0.1   192.168.0.10   300
2   192.168.0.1   192.168.0.20   400
3   192.168.0.1   192.168.0.30   300
4   10.152.0.13   167.10.2.187    80

我希望能够查询这个数据表,其中地址a是独一无二的,字节列求和(我不知道我是正确的说)。从本质上讲,我希望得到以下结果:

I'd like to be able to query this DataTable where AddressA is unique and the Bytes column is summed together (I'm not sure I'm saying that correctly). In essence, I'd like to get the following result:

1   192.168.0.1   1000
2   10.152.0.13     80

我最终想要这个结果是可以绑定到DataGrid一个DataTable,我需要更新/再生这个结果每5秒左右。

I ultimately want this result in a DataTable that can be bound to a DataGrid, and I need to update/regenerate this result every 5 seconds or so.

我如何做到这一点? DataTable.Select()方法?如果是这样,是什么在查询什么样子的?是否有替代/更好的方式来实现我的目标?

How do I do this? DataTable.Select() method? If so, what does the query look like? Is there an alternate/better way to achieve my goal?

编辑:我没有一个数据库。我简单地使用内存中的数据集来存储数据,因此一个纯粹的SQL解决方案将不会在这里工作。我试图找出如何在DataSet本身做到这一点。

I do not have a database. I'm simply using an in-memory DataSet to store the data, so a pure SQL solution won't work here. I'm trying to figure out how to do it within the DataSet itself.

推荐答案

有关可读性(因为我喜欢)我会尝试使用LINQ:

For readability (and because I love it) I would try to use LINQ:

var aggregatedAddresses = from DataRow row in dt.Rows
group row by row["AddressA"] into g
select new {
    Address = g.Key,
    Byte = g.Sum(row => (uint)row["Bytes"])
};

int i = 1;
foreach(var row in aggregatedAddresses)
{
    result.Rows.Add(i++, row.Address, row.Byte);
}

如果一个服务表现的问题被发现与LINQ解决方案,我会用手动解决方案去总结行的循环在原表和将它们插入到结果表中。

If a performace issue is discovered with the LINQ solution I would go with a manual solution summing up the rows in a loop over the original table and inserting them into the result table.

您也可以直接绑定把它变成一个DataTable的aggregatedAddresses到网格,而不是。

You can also bind the aggregatedAddresses directly to the grid instead of putting it into a DataTable.

这篇关于加入多个数据行到一个单一的DataRow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆