LINQ - Convert LINQ select to DataTable - c#

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

Related

Convert table name (in string) to use it in the LINQ query : C#, Entity Framework

I have a list of table names in form of strings. I want to loop through the list and use the table name in the LINQ query:
var db = new SomeContext();
// for a single table I can use the LINQ query as
var res = from q in db.Table
where ......
select q;
and it works just fine.
The above approach is hard coding. I need a generic solution for this to loop through multiple tables whose names are stored in a list.
// list of string containing table names
List<stringtableNames = [Get the table list from some source]
// not a problem here
loop through the table names and for each name execute a LINQ query as shown below
foreach(string table in tableNames)
{
var queryRes = from t in table
where <some_condition>
select t;
}
In the above statements "from t in table" above is not valid as "table" is a string. I need actual table object reference to use.
Need help on how do I go about doing that.
You can use the DbContext.Set method:
Set(System.Type.GetType("TableName"))
Above sentence will return a non generic DbSet. So, you will not be able to query with linq as usual. But you can use dynamic linq. ScottGu will explain it better than me.
Please, check this thread for other solutions.
In EF you can execute SQL Code.
In this example i use EF with SQL (String)
var db = new SomeContext();
var list = db.ExecuteStoreQuery<Obj>(Obj.sql);
class Obj
{
public const string sql = #"select [tbl].[field] from [tbl]";
}
select, where, from is one way to define LINQ but You can use it if you have a list of elements (IEnumerable<T> for example), but You have only name of Your table
I think You have to create a regular SQL query
foreach(string table in tableNames)
{
var query =$"select * from {table} where <some_condition>";
var list = db.ExecuteStoreQuery<Obj>(query);
}
In EF You can execute regular query

How to Create DataTable in LINQ

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

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

DataGridView binding to two tables

I have two tables. Most of the data is coming from the first table but there is a second table which has a column which I want to present in my UI
Here is my SQL Query
String sqlQuery = "SELECT u.CallerName, t.* FROM users u INNER JOIN tickets t ON u.id = t.user WHERE u.CallerName = 'tim.smith'";
I am using WinForms
If your query result is DataTable, then you can use Merge function to merge two table.
DataTable table1 = GetTable1Data(...);
DataTable table2 = GetTable2Data(...);
table1.Merge(table2, true);
Or if your query result is List, then you can use same approach as in DataTable case, using AddRange function:
List<YourClassType> list1 = GetList1Data(...);
List<YourClassType> list2 = GetList2Data(...);
list1.AddRange(list2, true);
It looks like you are doing just fine.
When binding with the DataGridView you can use:
Eval("CallerName")
to access the other column, but that column should work like all of the others.

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