如何在DataTableC#中选择布尔值

本文关键字:选择 布尔值 DataTableC# | 更新日期: 2023-09-27 18:28:36

我有一个数据库表,它有两列,如Name-varchar(50)和Valid-boolen

----------------
Name    Valid
----------------
John    True
John    False
----------------

只有当Name为"John"且Valid为"True"时,我才必须进行选择。我尝试了下面的代码,但没有返回任何东西。请在这方面帮助我。

conList = conTable.Select(string.Format(@"Name='{0}' AND Valid='True'", "John")).ToList();

如何在DataTableC#中选择布尔值

您可以使用LINQ(-To-DataTable):

var rows = from row in conTable.AsEnumerable()
           where row.Field<bool>("Valid") && row.Field<string>("Name") == "John"
           select row;

如果您想要从结果中获得新的DataTable,请使用:

DataTable filtered = rows.CopyToDataTable();

或者可以循环foreach中的行,或者使用ToArrayToList创建不同的集合。

通过方法语法实现一体化(效率不高):

DataTable filtered = conTable.AsEnumerable()
    .Where(row => row.Field<bool>("Valid") && row.Field<string>("Name") == "John")
    .CopyToDataTable();

您可以使用linq来实现这一点。示例如下。

List<DataRow> dataRows = (from DataRow dr in yourTable.Rows 
                          where (bool)dr["Valid"] == true && (string)dr["Name"] == "John" 
                          select dr).ToList();
dataRows.ForEach(p => Console.WriteLine("Name : {0}, Valid : {1}", p["Name"], p["Valid"]));
conList = conTable.Select(string.Format(@"Name='{0}' AND Valid", "John")).ToList();

如果Linq不是一个选项,则可以像过滤sql中包含位列的表一样过滤DataTable中的布尔列。

下面是我快速整理的一个样本,用于过滤包含bool 类型数据列的数据表

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Bit", typeof(bool));
dt.Rows.Add(1, true);
dt.Rows.Add(2, true);
dt.Rows.Add(3, false);
dt.Rows.Add(4, true);
// Fetch all columns that have bit set to true
var dr = dt.Select("Bit=1");
Console.WriteLine("ID'tBit");
foreach(DataRow r in dr)
{
 Console.WriteLine("{0}'t{1}", r["ID"], r["Bit"]);
}
Console.WriteLine();
// Fetch all columns that have bit set to false
dr=dt.Select("Bit=0");
Console.WriteLine("ID'tBit");
foreach (DataRow r in dr)
{
Console.WriteLine("{0}'t{1}", r["ID"], r["Bit"]);
}
Console.WriteLine();
Console.ReadLine();

我知道这个问题很老了,但这是我自己弄清楚之前的第一个搜索结果。