在C#中分组数据表 [英] grouping a datatable in C#
本文介绍了在C#中分组数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据表,其列值如下所示。我想用linq来做
IP InterfceName状态
1 。 1 。 1 。 1 int1 down
1 。 1 。 1 。 1 int2 up
1 。 1 。 1 。 1 int3 up
< span class =code-digit> 1 。 1 。 1 。 1 int4 up
1 。 1 。 1 。 2 int1 down
1 。 1 。 1 。 2 int2 notconneted
1 。 1 。 1 。 2 int3 up
1 。 1 。 1 。 3 int4 up
我想要一个新的输出数据表喜欢
IP状态计数
1 。 1 。 1 。 1 down 1
1 。 1 。 1 。 1 up 3
1 。 1 。 1 。 2 down 1
1 。 1 。 1 。 2 up 1
1 。 1 。 1 。 2 未连接 1
1 。 1 。 1 。 3 up 1
解决方案
你可以通过使用LINQ实现这一目标。查看以下链接,这将对您有所帮助。
按组划分的Linq查询 [ ^ ]
使用LINQ对来自DataTable的数据进行分组 [ ^ ]
试试这个:// 创建原始数据表的副本
Datatable dtCopy = new DataTable( );
dtCopy.Columns.Add( IP);
dtCopy.Columns.Add( Status);
dtCopy.Columns.Add( Count);
foreach (DataRow r in dtOriginal.Rows) // dtOriginal是原始数据表
{
bool matchFound = false ;
foreach (DataRow r1 in dtCopy.Rows)
{
if (r( IP) .ToString()= r1( IP)。ToString()&& r(< span class =code-string> Status)。ToString()= r1( 状态)。ToString())
{
int currentCount = 0 ;
int .TryParse(r1( Count )。ToString(),currentCount);
currentCount + = 1 ;
// 更新计数列
r1( Count)= currentCount.ToString();
matchFound = true ;
// 无需继续
破跨度>;
}
}
if (matchFound == false )
{
// 添加行
DataRow newRow = dtCopy.NewRow();
newRow( IP)= r( IP)。ToString();
newRow( Count)= r( 计数)。ToString();
newRow( Status)= r( 状态)。ToString();
dtCopy.Rows.Add(newRow);
}
}
没有测试代码但希望它有所帮助。
i have a datatable with columns values likes below. I want to do it with linq
IP InterfceName Status
1.1.1.1 int1 down
1.1.1.1 int2 up
1.1.1.1 int3 up
1.1.1.1 int4 up
1.1.1.2 int1 down
1.1.1.2 int2 notconneted
1.1.1.2 int3 up
1.1.1.3 int4 up
I want the a new output datatable to be like
IP Status Count
1.1.1.1 down 1
1.1.1.1 up 3
1.1.1.2 down 1
1.1.1.2 up 1
1.1.1.2 notconneted 1
1.1.1.3 up 1
解决方案
Hi,
you can achieve this by using LINQ. Review below links which will helps you.
Linq query to sum by group[^]
Use LINQ to group data from DataTable[^]
Try this :// Create a copy of the original datatable Datatable dtCopy = new DataTable() ; dtCopy.Columns.Add("IP"); dtCopy.Columns.Add("Status"); dtCopy.Columns.Add("Count"); foreach (DataRow r in dtOriginal.Rows) // dtOriginal is the original datatable { bool matchFound = false; foreach (DataRow r1 in dtCopy.Rows) { if(r("IP").ToString() = r1("IP").ToString() && r("Status").ToString() = r1("Status").ToString()) { int currentCount = 0 ; int.TryParse(r1("Count").ToString() , currentCount); currentCount+=1; //update the count column r1("Count") =currentCount.ToString(); matchFound= true; //No need to continue break; } } if (matchFound==false) { //add the row DataRow newRow = dtCopy.NewRow(); newRow("IP") = r("IP").ToString(); newRow("Count") = r("Count").ToString(); newRow("Status") = r("Status").ToString(); dtCopy.Rows.Add(newRow); } }
Did not test the code but hope it helps.
这篇关于在C#中分组数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文