[英]Datatable search by LINQ to avoid duplication
我在數據表中有一個空白行的列
Column1
A
B
C
D
E
我需要設置是否存在並避免添加,但不應計算空白行。 只有包含數據的行應該在(如果存在)中。 謝謝
bool exists = dt.Select().ToList().Exists(row => row["column1"].ToString() == txtbox)
if(exists == true)
{}
else
// 它包含空白所以它變為真,我需要的是不應該包含空白行。
var lignesNonContainEmptyString = dt.Select()
.Where(row => row["column1"] != null
&& row["column1"].ToString() == txtbox
&& !string.IsNullOrEmpty(row["column1"].ToString()))
bool exists = lignes.Count() != 0;
或者
bool exists = dt.Select()
.Any(row => row["column1"] != null
&& row["column1"].ToString() == txtbox
&& !string.IsNullOrEmpty(row["column1"].ToString()))
如果文本框為空,您希望返回false
,因此為文本框添加條件。
bool exists = !string.IsNullOrWhiteSpace(txtbox)
&& dt.Select().ToList()
.Exists(row => row["column1"].ToString() == txtbox)
順便說一句,您可以添加對System.Data.DataTableExtensions
的引用並使用擴展AsEnumerable
,而不是使用.Select().ToList()
:
dt.AsEnumerable().Any( .....
此代碼可以幫助您
from a in list where ( Column1 != null || Column1 != "")
&& Column1 == searchfield
select a
這個怎么樣:非 linq 方式
bool DataTableNonEmptyCount()
{
int count =0;
foreach (DataColumn col in row.Table.Columns)
if (!row.IsNull(col))
count ++;
return count;
}
這將返回列中所有非空行的計數。
根據 Thierry 的回答,您還可以使用Any(predicate) 語法:
var existsLineWithoutEmptyString =
dt.AsEnumerable()
.Any(row => row["column1"] != null
&& row["column1"].ToString() == txtbox
&& !string.IsNullOrEmpty(row["column1"].ToString()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.