How to Create DataTable in LINQ - c#

How to create DataTable in LINQ? In SQL Statements i used
DataTable dt;
dt = con.openDataTableQuery("SELECT TransactionID FROM HeaderTransaction");
How about in LINQ? Can you give an example?

Please see the documentation for LINQ to DataSet, examples can be found on the page.
The following is an example emulating your SQL code.
// Add a reference to System.Data.DataSetExtensions
// Query the headerTransaction table to select all items with TransactionID == 1, as an example, use your own value(s)
IEnumerable<DataRow> query =
from headers in headerTransaction.AsEnumerable()
where order.Field<int>("TransactionID") = 1
select order;
// Create a table from the query.
DataTable headersIdQuery = query.CopyToDataTable<DataRow>();
AsEnumerable() returns IEnumerable. As you asked for a DataTable, we convert IEnumerable to a DataTable, using CopyToDataTable().

Related

How to get particular DataTable using TableName?

One DataSet usually has lots of DataTable, but I'm only to target a particular DataTable which I thought it's pretty normal but apparently failed to do it?
Below were the approaches I've tried:
//Could not find an implementation of the query pattern for source type.......
DataTable dt = from table in changesDataSet.Tables
where table.TableName = "ABC"
select table;
//Surprisingly there was no method "Where" in changesDataSet.Tables
DataTable dt = changesDataSet.Tables.Where(x=>x.TableName="ABC").First();
Below was the code that able to print each and every table. I know I can do it via a loop but please tell me loop isn't the only options
foreach(DataTable table in changesDataSet.Tables)
{
Console.WriteLine(table.TableName);
}
You can access the table using an indexer on the collection of tables (DataTableCollection):
DataTable dt = changesDataSet.Tables["ABC"];

LINQ - Convert LINQ select to DataTable

I have a class that does some validation on the data. I want to reuse that class from a different place.
I cant change that class.
It goes something like:
public static List<string> Validate(DataTable CurrentMasterTable, Dictionary<string, string[]> LocalMasterRuleSet)
{...}
In its own it works just fine.
Issue is in the following. From another place in the project, to use that class, I must send it DataTable object, so it can do its magic.
How can I use LINQ, make selection on the table and send it as DataTable?
I have this code to begin with:
var listOfSinglePropertyNames = (from x in dbContext.tbl_mytable.AsEnumerable() select x);
IEnumerable<tbl_mytable> query = listOfSinglePropertyNames;
How do I convert the query to DataTable object? Reading other posts, I have seen I should use CopyToDataTable();
But I am not having any success.
Using LINQ to datatable. Adapt this code for your needings:
// Query the SalesOrderHeader table for orders placed
// after August 8, 2001.
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>();

LINQ Select From DataTable

Just started to play around with datatable and LINQ today.
I have a datatable that gets a list of Names From SQL database.
I am looking to return a specific name from the dt using LINQ.
I have tried the following code with no success at this. Is there something that i am doing wrong with the code.
dt returns a full list of names i am just looking to reduce the names down to one name. There is a name in the adventureworks database called Blade i am trying to display this only.
DataTable dt = DAL.GetNames();
try
{
var q = from myrow in dt.AsEnumerable()
where myrow.Field<string>("Name") =="Blade"
select myrow;
dataGridView1.DataSource = q;
}
I have tried to replace the == with a .equals.
I am totally new to the concept of using a Language intergrated query.
when i run the code noting happens i dont get any errors ect just no data returned.
You're defining your query but not actually running it.
Your line:
dataGridView1.DataSource = q;
Needs to be:
dataGridView1.DataSource = q.AsDataView();

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).

Querying inside a Dataset C#

I have an ADO.NET dataset which is set by a certain query,
say
SELECT ID,USER,PRODUCT,COUNT FROM PRODUCTION
Without using a where clause I need to derive some results from the dataset. Say I want to get the User and Product count of the user who has the maximum product count. (And I want to do it by using the existing dataset. I can't derive this from dataset.)
Any idea of a way to query inside the dataset? Since there are Datatables my thought was there is some way to query it.
Traditional SQL queries cannot be applied to the DataSet. The following is possible, however:
Filter rows using DataTable.Select. See here for detailed information about expressions in DataTables.
Calculate totals etc. using DataTable.Compute.
If these two don't do the trick, there's always LINQ.
Quick-and-dirty LINQ example: (which doesn't return a DataTable, but a list containing an anonymous type):
var joinedResult = dataTable1
// filtering:
.Select("MyColumn = 'value'")
// joining tables:
.Join(
dataTable2.AsEnumerable(),
row => row.Field<long>("PrimaryKeyField"),
row => row.Field<long?>("ForeignKeyField"),
// selecting a custom result:
(row1, row2) => new { AnotherColumn = row1.Field<string>("AnotherColumn") });
AsEnumerable converts a DataTable into an IEnumerable on which LINQ queries can be performed. If you are new to LINQ, check out this introduction.
Yes, you can use DataTable.Select method.
DataTable table = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "Date > #1/1/00#";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
Also see this link.
You can do cross-table queries of a Dataset object using LINQ to DataSet:
msdn.microsoft.com/en-us/library/bb386969.aspx

Categories

Resources