Linq 方法从数据表中仅选择一个条件?

问题描述 投票:0回答:1

拥有

DataTable
大量数据。我只需要从
AccType
,
 中选择一种类型 
DataTable

现在,如果存在带有 A,E,I,O,U 的帐户,并且如果我需要使用

'I'
选择帐户类型,我将通过
linq
方法从表中删除所有其他帐户。找到以下代码。

 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);
 }

我的问题是,根据优化过程,有什么简单的方法可以在一行中选择所需的帐户类型吗?

c# linq
1个回答
0
投票

您只需使用

Enumerable.Where
:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.