Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Like operator in Linq to DataTable?

I am using Linq to DataTable. How I can apply like operator in where clause. I want to do a search on data just as we have like operator in SQL.

I searched and tried the following code but got an error: Method 'Boolean Like(System.String, System.String)' cannot be used on the client; it is only for translation to SQL.

var details = from addresses in dt.AsEnumerable() 
    where SqlMethods.Like(prefixText, prefixText + "%") || SqlMethods.Like(prefixText, "%" + prefixText + "%")
    select (string) addresses["Details"];                      

return details.ToArray();
like image 508
haansi Avatar asked Dec 16 '10 17:12

haansi


People also ask

Can we use LINQ to query against a DataTable?

Can we use linq to query against a DataTable? Explanation: We cannot use query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable<T>. We need to use the AsEnumerable() extension for DataTable.

How do you like a query in LINQ?

In LINQ to SQL, we don't have a LIKE operator, but by using contains(), startswith(), and endswith() methods, we can implement LIKE operator functionality in LINQ to SQL.

Which method will be called for the DataTable of a DataSet in LINQ to DataSet query?

The CopyToDataTable method takes the results of a query and copies the data into a DataTable, which can then be used for data binding.

How do you get the first row in LINQ?

Solution 1. int id = 2; var item = lstData. FirstOrDefault(k => k.ID == id); if (item != null) { // use the Item object to read the properties. // your code here... }


2 Answers

Your best bet may be to re-write it as a regex an use

where yourRegex.IsMatch(row.SomeValue)

Or if it is just starts-with queries:

where row.SomeValue.StartsWith(prefix)
like image 146
Marc Gravell Avatar answered Nov 14 '22 15:11

Marc Gravell


var details = from addresses in dt.AsEnumerable()
                where addresses.Field<string>("Details").StartsWith(prefixText)
                ||  addresses.Field<string>("Details").Contains(prefixText)
                select addresses.Field<string>("Details");
like image 32
Tom Brothers Avatar answered Nov 14 '22 14:11

Tom Brothers