I have a database table with two columns such as Name -varchar(50) and Valid -boolen
----------------
Name Valid
----------------
John True
John False
----------------
I have to select only if Name is 'John' and Valid is 'True'. I tried the below code but it doesn't return any thing. Please help me in this regard.
conList = conTable.Select(string.Format(@"Name='{0}' AND Valid='True'", "John")).ToList();
You can use LINQ(-To-DataTable):
var rows = from row in conTable.AsEnumerable()
where row.Field<bool>("Valid") && row.Field<string>("Name") == "John"
select row;
If you want a new DataTable
from the result use:
DataTable filtered = rows.CopyToDataTable();
or you can loop the rows in a foreach
or create a different collection with ToArray
or ToList
.
All in one via method syntax (not more efficient):
DataTable filtered = conTable.AsEnumerable()
.Where(row => row.Field<bool>("Valid") && row.Field<string>("Name") == "John")
.CopyToDataTable();
conList = conTable.Select(string.Format(@"Name='{0}' AND Valid", "John")).ToList();
you can use linq for that. example is below.
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"]));
If Linq is not an option, you can filter boolean columns in a DataTable in the same way you would filter a table containing a bit column in sql.
Below is a sample I quickly put together to filter a datatable containing a data column of type 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();
I know the question is old but it was the first search result before figuring it out on my own.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.