how to run query on dataset? - c#

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.

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>();
}

Joining Values Of Two Columns From DataTable

Joining Values Of Two Columns From DataTable
Two columns make it in one columns from datatable
my datatable is
TagNumber, LogNumber Combined
124 1 2
125 1 3
126 2 4
o/p:
TagNumber
124 ~1~2
125 ~1~3
126 ~2~4
combined column is merge from column0 and column1
i dont understand hw can i do please write sample of code
I dont have experience on linq .
I add column bt hw can i merge two columns in that one columns
I got answer:
For i As Integer = 0 To dstemp.Tables(0).Rows.Count - 1
dstemp.Tables(0).Rows(i)(0) = dstemp.Tables(0).Rows(i)("TagNumber") & "~" & dstemp.Tables(0).Rows(i)("LogNumber") & "~" & dstemp.Tables(0).Rows(i)("Combined")
next
Try doing it like this.
dtTwoItems.Columns.Add("Combined", typeof(string), "TagNumber+'/'+LogNumber");
Ok if you really want to do this then you have create a extra DataTable with Three Columns:
TagNumber, LogNumber Combined:
as below:
private DataTable CreateDataTableColumns()
{
DataTable dtThreeItems = new DataTable();
dtThreeItems.Columns.Add("TagNumber", typeof(String));
dtThreeItems.Columns.Add("LogNumber", typeof(String));
dtThreeItems.Columns.Add("Combined", typeof(String));
return dtThreeItems;
}
Now iterate the old datatable as below to get combined value:
foreach (DataRow dr in dtTwoItems.Rows)
{
row = dtThreeItems.NewRow();
row["TagNumber"] = dr["TagNumber"].ToString();
row["LogNumber"] = dr["LogNumber"].ToString();
row["Combined"] = dr["TagNumber"].ToString()+"/"+dr["LogNumber"].ToString() ;
dtThreeItems.Rows.Add(row);
}
Thats All
DataTable is like a container.
It is not proper to join tables.
I recommend you'd use linq.
Did you try to Add new Column to DataTable and then iterate through Each Row to put value by combining them?
EDIT: I Am not sure if Linq or Datatable query have some inbuilt feature to do this, but simple solution is what I tell. Or if you are filling your datatable from any SQL Query based database, then write a SQL that has third column with merged value using concat of columns.
Edit2:
foreach (Datarow r in myTable.Rows) {
r["Newcolumn"] = Convert.ToString(r["c1"]) + "/" + Convert.ToString(r["c2"]);
}

Filtering entire DataSet with many DataTables

I have a DataSet with many DataTables each containing many columns plus a column buildingID.
I would like to filter the entire DataSet by giving it a value for buildingID. I would like the rows in every table with a buildingID of, say 343.
Is there any quick possible way in C#?
You can use DataTable.Select, which returns filtered rows from a DataTable matching a criteria.
foreach (DataTable table in dataset.Tables) {
var rows = table.Select("buildingID = " + buildingId.ToString());
// Do stuff with filtered rows
}
To easily get all the rows that match your criteria, here's a LINQ expression:
var rows = dataset.Tables.SelectMany(
t => t.Select("buildingID = " + buildingId.ToString()));
What about this?
var ds1 = new DataSet();
foreach (DataTable dt in ds1.Tables)
{
var filtereddt = dt.AsEnumerable().Where(row => row.Field<int>("buildingID") == 1).ToList();
//you can add these lists to another list array or something like that.
}

How to filter two DataTables in C#?

How to filter two tables in C#? Table one contains full data and table Two contains some content of Table one?
What exactly do you want to do (it's not clear from your question)? Take table1, filter it and then pass the result to table2?
Then:
DataView dv = table1.AsDataView();
dv.RowFilter = fexpression; // for example "MyID = 3"
DataTable table2 = dv.ToTable();
// If you want typed datatable, you can do it like this (although there are other ways):
MyTypedDataTable table2 = new MyTypedDataTable();
DataTable tempTable = dv.ToTable();
table2.Merge(tempTable);

How to go through two tables to create another table with common values

First Datatable is dt
var dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("First Name");
dt.Rows.Add(1,"name1");
dt.Rows.Add(6,"name6");
dt.Rows.Add(4,"name4");
The second table is dt2
var dt2 = new DataTable();
dt2.Columns.Add("ID");
dt2.Columns.Add("First Name");
dt2.Columns.Add("Last Name");
dt2.Columns.Add("Birthday");
dt2.Rows.Add(1,"name1", "lastName1", 01.01.1991);
dt2.Rows.Add(2,"name2", "lastName2", 02.02.1992);
dt2.Rows.Add(3,"name3", "lastName3", 03.03.1993);
dt2.Rows.Add(4,"name4", "lastName4", 04.04.1994);
dt2.Rows.Add(5,"name5", "lastName5", 05.05.1995);
dt2.Rows.Add(6,"name6", "lastName6", 06.06.1996);
in the third DataTable dt3, I want to get those values ​​where ID is the same
result:
ID Name Birthdate
1 name1 01.01.1991
4 name4 04.04.1994
6 name6 06.06.1996
how to go through the DataTable's in c# ?
Unfortunately, there's no easy way, AFAIK, to join the 2 tables and get the third table automagically unless you are willing to write some code....
You can join them using Linq first:
var common = from c in dt.AsEnumerable()
join x in dt2.AsEnumerable() on c.Field<string>("ID") equals x.Field<string>("ID")
select new object[] { c["ID"],c["First Name"], x["Birthday"] };
And now you can create the destination table with the schema you want:
DataTable dt3 = new DataTable();
dt3.Columns.Add("ID");
dt3.Columns.Add("Name");
dt3.Columns.Add("Birthdate");
foreach (var item in common)
dt3.LoadDataRow(item.ToArray(),true);
Write an SQL Query or a Stored Procedure such that it joins the Two tables like you have depicted. Now use that Query for your DataTable with in .Net. You will get what you need.
Are you adding them to an actual database with a defined schema or just trying to do this in memory? If memory, I would add these to a DataSet which you can then use to filter the criteria becuase in the dataset, you can define their relationship.
You might be looking for adding Relationship between your tables. Check this link.
I guess you will need the DataTables to be in the same DataSet (you can add the DataTables into DataSet).

Categories

Resources