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?
>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.