LIKE query on DataTable using LINQ - c#

Ive just started learning Linq. Ive just created a sample test like this.
Dim dt As New DataTable
Dim dc As New DataColumn
dc.ColumnName = "Test"
dt.Columns.Add(dc)
dt.Rows.Add("Test")
dt.Rows.Add("One test")
dt.Rows.Add("Second test")
Dim results = From myRow In dt.AsEnumerable
Where myRow("Test") = "Test"
Select myRow
For Each Row In results
Console.WriteLine(Row.Item(0).ToString())
Next
This returns the first row in the iteration.
But what if i want to use a LIKE operator using %? I cant get it to work.
Ive tried
Where myRow("Test") LIKE "Test%"

Sounds to me like you want to use StartsWith i.e.
Dim results = From myRow In dt.AsEnumerable
Where myRow("Test").StartsWith("Test")
Select myRow
Contains will match anywhere in the string where as StartsWith will only match if it's at the beginning of the string (same logic as Test%).

You migh be looking for contains.
Take a look at this:
var query = from mem in context.Member
where mem.LastName.Contains("xxx")
orderby mem.LastName, mem.FirstName
select new
{
FirstName = mem.FirstName,
LastName = mem.LastName,
};
You can also use .StartsWith() or .EndsWith().

You can use the contains method:
Dim results = From myRow In dt.AsEnumerable
Where myRow("Test").Contains("Test")
Select myRow

Related

Filtering Out Rows That Match a Search String in a Data Table - C# [duplicate]

I use a DataTable with Information about Users and I want search a user or a list of users in this DataTable. I try it butit don't work :(
Here is my c# code:
public DataTable GetEntriesBySearch(string username,string location,DataTable table)
{
list = null;
list = table;
string expression;
string sortOrder;
expression = "Nachname = 'test'";
sortOrder = "nachname DESC";
DataRow[] rows = list.Select(expression, sortOrder);
list = null; // for testing
list = new DataTable(); // for testing
foreach (DataRow row in rows)
{
list.ImportRow(row);
}
return list;
}
You can use DataView.
DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"
http://www.csharp-examples.net/dataview-rowfilter/
If you're using at least .NET 3.5, i would suggest to use Linq-To-DataTable instead since it's much more readable and powerful:
DataTable tblFiltered = table.AsEnumerable()
.Where(row => row.Field<String>("Nachname") == username
&& row.Field<String>("Ort") == location)
.OrderByDescending(row => row.Field<String>("Nachname"))
.CopyToDataTable();
Above code is just an example, actually you have many more methods available.
Remember to add using System.Linq; and for the AsEnumerable extension method a reference to the System.Data.DataSetExtensions dll (How).
use it:
.CopyToDataTable()
example:
string _sqlWhere = "Nachname = 'test'";
string _sqlOrder = "Nachname DESC";
DataTable _newDataTable = yurDateTable.Select(_sqlWhere, _sqlOrder).CopyToDataTable();
Sometimes you actually want to return a DataTable than a DataView. So a DataView was not good in my case and I guess few others would want that too. Here is what I used to do
myDataTable.select("myquery").CopyToDataTable()
This will filter myDataTable which is a DataTable and return a new DataTable
Hope someone will find that is useful
For anybody who work in VB.NET (just in case)
Dim dv As DataView = yourDatatable.DefaultView
dv.RowFilter ="query" ' ex: "parentid = 0"
It is better to use DataView for this task.
Example of the using it you can find in this post: How to filter data in dataview
Hi we can use ToLower Method sometimes it is not filter.
EmployeeId = Session["EmployeeID"].ToString();
var rows = dtCrewList.AsEnumerable().Where
(row => row.Field<string>("EmployeeId").ToLower()== EmployeeId.ToLower());
if (rows.Any())
{
tblFiltered = rows.CopyToDataTable<DataRow>();
}

Error when Copying Query from linq to Datatable

I just started working on a project that requires Linq to Sql, and I have been able to make queries and retrieve data. But right now I need to fill a DataTable with the data I am retrieving.
My first code was the following:
MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
where cust.CustomerName != "Dante"
orderby cust.CustomerName
select new { Name = cust.CustomerName };
So, since I needed to copy the content of my query to a Datatable I tried this:
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();
Then, my code looks like this:
IEnumerable<DataRow> myQuery = from cust in db.Customers.AsEnumerable()
where cust.Name != "Dante"
orderby cust.Name
select new { Name = cust.Name };
DataTable myDataTable = myQuery.CopyToDataTable<DataRow>();
But with this code the compiler raises and error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Data.DataRow>
The error is raised at the select word.
So, What am I doing wrong?? What can I do in order to avoid this conversion issue?
Hope someone can help me, thanks in advance.
There is a way to create a DataTable from a result other than IEnumerable<DataRow>, but it is rather involved. Implement CopyToDataTable Where the Generic Type T Is Not a DataRow.
For your case, though, I would recommend doing it the following way. Go back to your original query:
MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
where cust.CustomerName != "Dante"
orderby cust.CustomerName
select new { Name = cust.CustomerName };
Then define your single field DataTable because when you eventually create a DataRow, it needs a schema to work from:
DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(
new DataColumn()
{
DataType = System.Type.GetType("System.String"),
ColumnName = "Name"
}
);
And finally, go through the results of your query and manually add the DataRows to your DataTable.
foreach (var element in query)
{
var row = myDataTable.NewRow();
row["Name"] = element.Name;
myDataTable.Rows.Add(row);
}
The problem is exactly as the error states; your "select" clause is creating instances of an anonymous type with one member, "Name". This anonymous type is not and cannot be a DataRow, so the implicit conversion between what the query produces and the variable you want to set it into fails.
Instead, you should take this query, and for each element of the anonymous type that it returns, add the value as a new DataRow of the DataTable. You cannot just create a new DataRow from scratch; the DataRow class requires a context, namely the parent DataTable, to define the columns the DataRow should have.
This will do i guess
var myQuery = from cust in db.Customers.AsEnumerable()
where cust.Name != "Dante"
orderby cust.Name
select new { Name = cust.Name };
or try this
string[] myQuery = db.Customers.Rows
.Cast<DataRow>()
.Where(r=>r.Name!="Dante")
.Orderby(r=>r.Name)
.Select(r=>r.Field<string>("Name"))
.ToArray()

How to select a field with linq on datarow

I have this linq query :
string title = from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title;
and I'd like to extract the field Title (from Database) on the row (rows will be 1, not more, so that's I put on a string and not in a string[].
How can I do it?
VStudio says that DataRow doesnt contain the definition of Title, but the field Title exist on the database.
I making confusion :)
As Frédéric Hamidi said, you don't need LINQ.
However, if you still want to do it that way (overkill) and you know that there is always a single table with a single row, do:
DataSet data = new DataSet();
var table = (from a in data.Tables.Cast<DataTable>() select a).Single();
var row = (from a in table.Rows.Cast<DataRow>() select a).Single();
String title = row.Field<String>("Title");
or
DataSet data = new DataSet();
var table = (from a in data.Tables.Cast<DataTable>() select a).SingleOrDefault();
var row = (from a in table.Rows.Cast<DataRow>() select a).SingleOrDefault();
String title = row.Field<String>("Title");
I used a DataSet because I don't know how your object is structured.
You don't need LINQ since you only want to fetch the Title field of the first row in the collection:
string title = OleDB.DataItems.Tables[0].Rows[0]["Title"];
try
string title = (from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title).First();
Linq returns an enumerable collection as it doesn't know there will be only one item. Calling the First method will return the first item from the query.
Edit: Hang on, I have blatantly missed the problem you originally mentioned (but you'll still need the above)!
A data row contains fields, not properties as such. What you'll need to do is
select r.Field<string>("Title")
So your entire query will be
string title = (from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Field<string>("Title")).First();
It's better to use FirstOrDefault, in case there are no rows:
string title = (from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title).FirstOrDefault();
Usually, if you need to perform such an action, you would cast the DataRow object to your strongly typed object corresponding with the table in your database.
I assume there is a class "Book" which contains the field "Title":
Book selectedBook = (Book) from DataRow r in (OleDB.DataItems.Tables[0]).Rows[0]
string sTitle = selectedBook.Title;
Hope this helps.

how to run query on dataset?

I have a DataSet named dsView that contains data. Here is the code i use to read the XML:
dsView = new DataSet();
dsView.ReadXml(#"\c:MyXml.xml");
The data has a table named MEN with fields Fname and Lname. How do I run a query on this dsView? (for example: select * from MEN where Fname = 'zz')
You cannot run complete SQL statements on a DataSet - but the DataTable inside your DataSet does have a method called Select(string) which selects an array of DataRow object that match a certain criteria.
Check out the MSDN docs on DataTable
You would probably have to do something like (untested):
DataTable tblMEN = dsView.Tables["MEN"];
DataRow[] results = tblMen.Select("Fname = 'zz'");
I don't think you can run a SQL query on a DataSet, since it doesn't have a query engine. But you could try LINQ to DataSet.
Also, if you are only interested in the data (and not the databinding properties of the DataSet), I suggest you use LINQ to XML to query the document.
dsView.Table[0].DefaultView.RowFilter = "Fname = 'zz'";
// now default view contains the filtered rows
//ds.Table[0].DefaultView
More about DefaultVeiw on msdn
AFAIK You can only run a Sql Like query on a DataTable with the Select method.
You would use this overload of DataTable.Select here to do something like this:
DataRow[] foundRows = dsView.Table[0].Select("Fname = `zz`");
dsView.Table[0] should point to the table of MEN and should have a column Fname
The expressions valid are the same as DataColumn expressions:
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx
Here is an example that I used to make a menu.
Dim dstpage As DataSet
dstpage = businessService.GetData()
Dim userTable As DataTable
userTable = dstpage.Tables(0)
If userTable.Rows.Count > 0 Then
Dim results As DataRow()
results = userTable.Select("PAGE_GROUP_NAME='People'")
For i As Integer = 0 To results.Count - 1
FilePath = userTable.Rows(i)("FILE_PATH").ToString()
PageName = userTable.Rows(i)("PAGE_NAME").ToString()
Next
End If
// Create a table of five different people.
// ... Store their size and sex.
DataTable table = new DataTable("Players");
table.Columns.Add(new DataColumn("Size", typeof(int)));
table.Columns.Add(new DataColumn("Sex", typeof(char)));
table.Rows.Add(100, 'f');
table.Rows.Add(235, 'f');
table.Rows.Add(250, 'm');
table.Rows.Add(310, 'm');
table.Rows.Add(150, 'm');
// Search for people above a certain size.
// ... Require certain sex.
DataRow[] result = table.Select("Size >= 230 AND Sex = 'm'");
foreach (DataRow row in result)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
you can use this code.i hope it's help you.

how to run query on dataset?

i have Dataset that contain any database.
how to run any query on this dataset ?
You could use a DataView:
var view = new DataView(dataSet.Tables("TableName"));
view.RowFilter = "ColumnName LIKE '%something%'"
foreach (var row in view.Rows)
{
// do something
}
or LINQ:
var results = from row in dataSet.Tables("Table").AsEnumerable()
where row.Field(Of String)("ColumnName").Contains("something")
select row;
foreach (var row in results)
{
// do something
}
Google should suffice for a question like this...
Hi I believe you can use Linq To Objects to query this dataset:
var results = (from r in mydatasetvar.AsQuarieable() .. )
See this for more info
Alternatively, you can loop through the tables, rows and columns of the dataset.

Categories

Resources