Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a datatable with columns values likes below. I want to do it with linq

C#
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
C#
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
Posted
Updated 16-Nov-14 20:30pm
v2

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[^]
 
Share this answer
 
Comments
BillWoodruff 18-Nov-14 3:53am    
+5 It's really good see someone posting links that are so directly relevant to the OP's question !
Try this :
C#
// 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.
 
Share this answer
 
v2
Comments
BillWoodruff 18-Nov-14 3:57am    
Putting code you don't know works and that contains obvious errors like using a DataTable (dtCopy) that has no data in it as if it does contain data ... just wastes everybody's time.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900