Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linq method to select only one condition from a datatable?

Having DataTable with bulk of data. and i need to select only one type of AccType from the DataTable ,

Right now, if there is Accounts with A,E,I,O,U and if, i need to select an account type with 'I' I will remove all other Accounts from the table via linq method. find the following code.

 DataTable dt = (DataTable)this.ViewState["Account"];
 CopyTAble = dt.Copy();
 SeledAcc = CopyTAble;
 DataRow[] rows;
 string AccType = "";
 if (dt != null)
 {
     string AType = "E";
     string BType = "A";
     string CType = "U";
     string DType = "O";
     string EType = "I";
     
     if (AccType == "I")
     {
         rows = SeledAcc.Select("AccType = '" + AType + "'");  
         foreach (DataRow row in rows)
             SeledAcc.Rows.Remove(row);
         rows = SeledAcc.Select("AccType = '" + BType + "'");  
         foreach (DataRow row in rows)
             SeledAcc.Rows.Remove(row);
         rows = SeledAcc.Select("AccType = '" + CType + "'"); 
         foreach (DataRow row in rows)
             SeledAcc.Rows.Remove(row);
         rows = SeledAcc.Select("AccType = '" + DType + "'");  
         foreach (DataRow row in rows)
             SeledAcc.Rows.Remove(row);
     }
    }

My question as per the optimization process, there is any simple way to select the desired account type in a single line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Enumerable.Where and CopyToDataTable:

DataTable matchingRowsTable;
try
{
    matchingRowsTable = SeledAcc.AsEnumerable()
        .Where(row => row.Field<string>("AccType") == AccType)
        .CopyToDataTable();
}
catch (InvalidOperationException) // thrown if there were no matching rows
{
    matchingRowsTable = SeledAcc.Clone(); // empty table with same columns
}

I have handled the InvalidOperationException because it’s thrown in CopyToDataTable if there are no matching rows. This is the most efficient way to handle this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading