简体   繁体   中英

Datatable search by LINQ to avoid duplication

I have a column in dataTable with blank rows

Column1
A
B
C

D

E

I need to set if exist and to avoid adding, but blank rows should not be counted. Only rows with data should be in the (if exists). Thanks

 bool exists = dt.Select().ToList().Exists(row => row["column1"].ToString() == txtbox)



if(exists == true)
{}
else

// it includes blank so it goes to true, which I need is blank rows should not be included.

var lignesNonContainEmptyString = dt.Select()
                   .Where(row => row["column1"] != null 
                                && row["column1"].ToString() == txtbox 
                                && !string.IsNullOrEmpty(row["column1"].ToString()))

bool exists = lignes.Count() != 0;

OR

bool exists = dt.Select()
                       .Any(row => row["column1"] != null 
                                    && row["column1"].ToString() == txtbox 
                                    && !string.IsNullOrEmpty(row["column1"].ToString()))

You would like to return false if the textbox is empty, so add the condition for the textbox.

bool exists = !string.IsNullOrWhiteSpace(txtbox)
              && dt.Select().ToList()
                   .Exists(row => row["column1"].ToString() == txtbox)

By the way, instead of using .Select().ToList() , you can add a reference to System.Data.DataTableExtensions and use the Extension AsEnumerable :

dt.AsEnumerable().Any( .....

this code can help you

from a in list where ( Column1 != null || Column1 != "")
&& Column1 == searchfield
select a

How about this: non linq way

bool DataTableNonEmptyCount()
{
int count =0;
foreach (DataColumn col in row.Table.Columns)
    if (!row.IsNull(col))
      count ++;

  return count;
}

This will return a count of all non null row in column.

Based on Thierry's answer , you can also use the Any(predicate) syntax :

var existsLineWithoutEmptyString = 
             dt.AsEnumerable()
               .Any(row => row["column1"] != null 
                           && row["column1"].ToString() == txtbox 
                           && !string.IsNullOrEmpty(row["column1"].ToString()))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM