将多个 DataRow 加入单个 DataRow [英] Join multiple DataRows into a single DataRow

查看:22
本文介绍了将多个 DataRow 加入单个 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

我希望能够查询此 DataTable,其中 AddressA 是唯一的,并且 Bytes 列被加在一起(我不确定我说的是否正确).本质上,我想得到以下结果:

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?

我没有数据库.我只是使用内存中的 DataSet 来存储数据,因此纯 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.

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

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

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