How to apply a SQL statement on one or more DataTable's?Linq: GroupBy, Sum and CountHow to receive a SQL-Statement as a DataTableHow can I prevent SQL injection in PHP?How do I perform an IF…THEN in an SQL SELECT?Add a column with a default value to an existing table in SQL ServerHow do I enumerate an enum in C#?How to return only the Date from a SQL Server DateTime datatypeInserting multiple rows in a single SQL query?How can I do an UPDATE statement with JOIN in SQL?How do I UPDATE from a SELECT in SQL Server?Finding duplicate values in a SQL tableHow to import an SQL file using the command line in MySQL?

Why isn't UDP with reliability (implemented at Application layer) a substitute of TCP?

How do banks maintain reserves?

Hard for me to understand one tip written in "The as-if rule" of cppreference

Where to connect the fuse and why?

Customs and immigration on a USA-UK-Sweden flight itinerary

Why are examinees often not allowed to leave during the start and end of an exam?

Does "boire un jus" tend to mean "coffee" or "juice of fruit"?

Can dual citizens open crypto exchange accounts where U.S. citizens are prohibited?

Correct use of the the idiom 'Гнать/Катить бочку'

Journal standards vs. personal standards

How do I keep a running total of data in a column in Excel?

Why were the first airplanes "backwards"?

Is having 4 bed leveling adjustment points rather than 3 problematic?

Have any large aeroplanes been landed — safely and without damage — in locations that they could not be flown away from?

Is my guitar action too high or is the bridge too high?

"I am [the / an] owner of a bookstore"?

What election rules and voting rights are guaranteed by the US Constitution?

Calculus, water poured into a cone: Why is the derivative non-linear?

English idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)

Fast method to cut/shred glue stick into small pieces

Why will we fail creating a self sustaining off world colony?

How useful would a hydroelectric power plant be in the post-apocalypse world?

Did the Russian Empire have a claim to Sweden? Was there ever a time where they could have pursued it?

Is it advisable to inform the CEO about his brother accessing his office?



How to apply a SQL statement on one or more DataTable's?


Linq: GroupBy, Sum and CountHow to receive a SQL-Statement as a DataTableHow can I prevent SQL injection in PHP?How do I perform an IF…THEN in an SQL SELECT?Add a column with a default value to an existing table in SQL ServerHow do I enumerate an enum in C#?How to return only the Date from a SQL Server DateTime datatypeInserting multiple rows in a single SQL query?How can I do an UPDATE statement with JOIN in SQL?How do I UPDATE from a SELECT in SQL Server?Finding duplicate values in a SQL tableHow to import an SQL file using the command line in MySQL?













0















Question



Please help me writing a C# or vb.net routine that will accept



  • a DataTable

  • a SQL query as a string

and create



  • a DataTable with the result of the query applied to the in put DataTable

To my knowledge, the tool to run SQL in .net is linq, but this does not lead me to a sollution.



In VB.net terms: How do I implement a function like this



Public Function SelectFromDataTable(Sql As String, T1 As DataTable) As DataTable
// Apply Sql to T1
End Function


(or even better, like this)



Public Function SelectFromDataTable(Sql As String, T1 As DataTable, Optional T2 As DataTable) As DataTable
// Apply Sql to T1 and T2
End Function


What I tried so far



For some reason, I thought linq could be the solution, but that is no requirement.



Trial 1



if I look for the combination of linq and DataTable's I get that typicle syntax in which you write sql-like code inline in your .net code, as on. Queries in LINQ to DataSet



I want the query to be defined outside my routine,so can you also create such queries from a SQL string?



Trial 2



Looking for the combination of linq and SQL, I get examples using a SqlDataAdapter, but they need a SqlConnection, which apparently must point to a database, as in How to receive a SQL-Statement as a DataTable



However, for me, not only the destination, but also the source should be a DataTable, so can you also create a SqlConnection to DataTables?



Context



If you are curious where my question comes from:



BluePrism is a graphic Robotic Process Automation (RPA) tool. It has one container object, called a collection, which is under the hood a .net DataTable and gives verry little support to manipulate these.



Fortunately, one can create so called "business objects" in .net and implements "Action" that receive and return variables. (This is meant to manipulate other applications, but can also be used to manipulate data.)



We already have such an object, which we called Collection Manipulation. One of the actions, Filter Collection, is implemented as



Dim NewRow As DataRow

Collection_Out = Collection_In.Clone

For Each parentRow As DataRow In Collection_In.Select(Select_Condition)
NewRow = Collection_Out.NewRow
For Each c As DataColumn In NewRow.Table.Columns
NewRow(c.ColumnName) = parentRow(c.ColumnName)
Next
Collection_Out.Rows.Add(NewRow)
Next

NewRow = Nothing
Collection_In = Nothing


I would like to implement a general purpose Action, to runs queries against my collection like



select category, sum(unit_price * units) as total_price 
from invoice
group by category;

select article, order.units - delivery.units as units_missing
from order, delivery
where order.article = delivery.article;









share|improve this question
























  • Can you use the DataTable.Slect method to filter out rows with a string? What type of queries do you need?

    – NetMage
    Mar 25 at 19:05











  • Thanks, I edited the Context section of the question for you.

    – Dirk Horsten
    Mar 26 at 8:52











  • Does linq allow to store/view DataTables "as data base tables" and query them, even if you have no real data base?

    – Dirk Horsten
    Mar 26 at 9:16











  • can you directly use OLEDB methods on your data source or paste your collections into excel run the SQL query?

    – Josh
    Mar 27 at 13:10











  • My datasource are DataTables. Can I use OLEDB without a database?

    – Dirk Horsten
    Mar 27 at 13:46
















0















Question



Please help me writing a C# or vb.net routine that will accept



  • a DataTable

  • a SQL query as a string

and create



  • a DataTable with the result of the query applied to the in put DataTable

To my knowledge, the tool to run SQL in .net is linq, but this does not lead me to a sollution.



In VB.net terms: How do I implement a function like this



Public Function SelectFromDataTable(Sql As String, T1 As DataTable) As DataTable
// Apply Sql to T1
End Function


(or even better, like this)



Public Function SelectFromDataTable(Sql As String, T1 As DataTable, Optional T2 As DataTable) As DataTable
// Apply Sql to T1 and T2
End Function


What I tried so far



For some reason, I thought linq could be the solution, but that is no requirement.



Trial 1



if I look for the combination of linq and DataTable's I get that typicle syntax in which you write sql-like code inline in your .net code, as on. Queries in LINQ to DataSet



I want the query to be defined outside my routine,so can you also create such queries from a SQL string?



Trial 2



Looking for the combination of linq and SQL, I get examples using a SqlDataAdapter, but they need a SqlConnection, which apparently must point to a database, as in How to receive a SQL-Statement as a DataTable



However, for me, not only the destination, but also the source should be a DataTable, so can you also create a SqlConnection to DataTables?



Context



If you are curious where my question comes from:



BluePrism is a graphic Robotic Process Automation (RPA) tool. It has one container object, called a collection, which is under the hood a .net DataTable and gives verry little support to manipulate these.



Fortunately, one can create so called "business objects" in .net and implements "Action" that receive and return variables. (This is meant to manipulate other applications, but can also be used to manipulate data.)



We already have such an object, which we called Collection Manipulation. One of the actions, Filter Collection, is implemented as



Dim NewRow As DataRow

Collection_Out = Collection_In.Clone

For Each parentRow As DataRow In Collection_In.Select(Select_Condition)
NewRow = Collection_Out.NewRow
For Each c As DataColumn In NewRow.Table.Columns
NewRow(c.ColumnName) = parentRow(c.ColumnName)
Next
Collection_Out.Rows.Add(NewRow)
Next

NewRow = Nothing
Collection_In = Nothing


I would like to implement a general purpose Action, to runs queries against my collection like



select category, sum(unit_price * units) as total_price 
from invoice
group by category;

select article, order.units - delivery.units as units_missing
from order, delivery
where order.article = delivery.article;









share|improve this question
























  • Can you use the DataTable.Slect method to filter out rows with a string? What type of queries do you need?

    – NetMage
    Mar 25 at 19:05











  • Thanks, I edited the Context section of the question for you.

    – Dirk Horsten
    Mar 26 at 8:52











  • Does linq allow to store/view DataTables "as data base tables" and query them, even if you have no real data base?

    – Dirk Horsten
    Mar 26 at 9:16











  • can you directly use OLEDB methods on your data source or paste your collections into excel run the SQL query?

    – Josh
    Mar 27 at 13:10











  • My datasource are DataTables. Can I use OLEDB without a database?

    – Dirk Horsten
    Mar 27 at 13:46














0












0








0








Question



Please help me writing a C# or vb.net routine that will accept



  • a DataTable

  • a SQL query as a string

and create



  • a DataTable with the result of the query applied to the in put DataTable

To my knowledge, the tool to run SQL in .net is linq, but this does not lead me to a sollution.



In VB.net terms: How do I implement a function like this



Public Function SelectFromDataTable(Sql As String, T1 As DataTable) As DataTable
// Apply Sql to T1
End Function


(or even better, like this)



Public Function SelectFromDataTable(Sql As String, T1 As DataTable, Optional T2 As DataTable) As DataTable
// Apply Sql to T1 and T2
End Function


What I tried so far



For some reason, I thought linq could be the solution, but that is no requirement.



Trial 1



if I look for the combination of linq and DataTable's I get that typicle syntax in which you write sql-like code inline in your .net code, as on. Queries in LINQ to DataSet



I want the query to be defined outside my routine,so can you also create such queries from a SQL string?



Trial 2



Looking for the combination of linq and SQL, I get examples using a SqlDataAdapter, but they need a SqlConnection, which apparently must point to a database, as in How to receive a SQL-Statement as a DataTable



However, for me, not only the destination, but also the source should be a DataTable, so can you also create a SqlConnection to DataTables?



Context



If you are curious where my question comes from:



BluePrism is a graphic Robotic Process Automation (RPA) tool. It has one container object, called a collection, which is under the hood a .net DataTable and gives verry little support to manipulate these.



Fortunately, one can create so called "business objects" in .net and implements "Action" that receive and return variables. (This is meant to manipulate other applications, but can also be used to manipulate data.)



We already have such an object, which we called Collection Manipulation. One of the actions, Filter Collection, is implemented as



Dim NewRow As DataRow

Collection_Out = Collection_In.Clone

For Each parentRow As DataRow In Collection_In.Select(Select_Condition)
NewRow = Collection_Out.NewRow
For Each c As DataColumn In NewRow.Table.Columns
NewRow(c.ColumnName) = parentRow(c.ColumnName)
Next
Collection_Out.Rows.Add(NewRow)
Next

NewRow = Nothing
Collection_In = Nothing


I would like to implement a general purpose Action, to runs queries against my collection like



select category, sum(unit_price * units) as total_price 
from invoice
group by category;

select article, order.units - delivery.units as units_missing
from order, delivery
where order.article = delivery.article;









share|improve this question
















Question



Please help me writing a C# or vb.net routine that will accept



  • a DataTable

  • a SQL query as a string

and create



  • a DataTable with the result of the query applied to the in put DataTable

To my knowledge, the tool to run SQL in .net is linq, but this does not lead me to a sollution.



In VB.net terms: How do I implement a function like this



Public Function SelectFromDataTable(Sql As String, T1 As DataTable) As DataTable
// Apply Sql to T1
End Function


(or even better, like this)



Public Function SelectFromDataTable(Sql As String, T1 As DataTable, Optional T2 As DataTable) As DataTable
// Apply Sql to T1 and T2
End Function


What I tried so far



For some reason, I thought linq could be the solution, but that is no requirement.



Trial 1



if I look for the combination of linq and DataTable's I get that typicle syntax in which you write sql-like code inline in your .net code, as on. Queries in LINQ to DataSet



I want the query to be defined outside my routine,so can you also create such queries from a SQL string?



Trial 2



Looking for the combination of linq and SQL, I get examples using a SqlDataAdapter, but they need a SqlConnection, which apparently must point to a database, as in How to receive a SQL-Statement as a DataTable



However, for me, not only the destination, but also the source should be a DataTable, so can you also create a SqlConnection to DataTables?



Context



If you are curious where my question comes from:



BluePrism is a graphic Robotic Process Automation (RPA) tool. It has one container object, called a collection, which is under the hood a .net DataTable and gives verry little support to manipulate these.



Fortunately, one can create so called "business objects" in .net and implements "Action" that receive and return variables. (This is meant to manipulate other applications, but can also be used to manipulate data.)



We already have such an object, which we called Collection Manipulation. One of the actions, Filter Collection, is implemented as



Dim NewRow As DataRow

Collection_Out = Collection_In.Clone

For Each parentRow As DataRow In Collection_In.Select(Select_Condition)
NewRow = Collection_Out.NewRow
For Each c As DataColumn In NewRow.Table.Columns
NewRow(c.ColumnName) = parentRow(c.ColumnName)
Next
Collection_Out.Rows.Add(NewRow)
Next

NewRow = Nothing
Collection_In = Nothing


I would like to implement a general purpose Action, to runs queries against my collection like



select category, sum(unit_price * units) as total_price 
from invoice
group by category;

select article, order.units - delivery.units as units_missing
from order, delivery
where order.article = delivery.article;






sql .net linq datatable blueprism






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 21:41







Dirk Horsten

















asked Mar 25 at 15:40









Dirk HorstenDirk Horsten

2,2973 gold badges14 silver badges30 bronze badges




2,2973 gold badges14 silver badges30 bronze badges












  • Can you use the DataTable.Slect method to filter out rows with a string? What type of queries do you need?

    – NetMage
    Mar 25 at 19:05











  • Thanks, I edited the Context section of the question for you.

    – Dirk Horsten
    Mar 26 at 8:52











  • Does linq allow to store/view DataTables "as data base tables" and query them, even if you have no real data base?

    – Dirk Horsten
    Mar 26 at 9:16











  • can you directly use OLEDB methods on your data source or paste your collections into excel run the SQL query?

    – Josh
    Mar 27 at 13:10











  • My datasource are DataTables. Can I use OLEDB without a database?

    – Dirk Horsten
    Mar 27 at 13:46


















  • Can you use the DataTable.Slect method to filter out rows with a string? What type of queries do you need?

    – NetMage
    Mar 25 at 19:05











  • Thanks, I edited the Context section of the question for you.

    – Dirk Horsten
    Mar 26 at 8:52











  • Does linq allow to store/view DataTables "as data base tables" and query them, even if you have no real data base?

    – Dirk Horsten
    Mar 26 at 9:16











  • can you directly use OLEDB methods on your data source or paste your collections into excel run the SQL query?

    – Josh
    Mar 27 at 13:10











  • My datasource are DataTables. Can I use OLEDB without a database?

    – Dirk Horsten
    Mar 27 at 13:46

















Can you use the DataTable.Slect method to filter out rows with a string? What type of queries do you need?

– NetMage
Mar 25 at 19:05





Can you use the DataTable.Slect method to filter out rows with a string? What type of queries do you need?

– NetMage
Mar 25 at 19:05













Thanks, I edited the Context section of the question for you.

– Dirk Horsten
Mar 26 at 8:52





Thanks, I edited the Context section of the question for you.

– Dirk Horsten
Mar 26 at 8:52













Does linq allow to store/view DataTables "as data base tables" and query them, even if you have no real data base?

– Dirk Horsten
Mar 26 at 9:16





Does linq allow to store/view DataTables "as data base tables" and query them, even if you have no real data base?

– Dirk Horsten
Mar 26 at 9:16













can you directly use OLEDB methods on your data source or paste your collections into excel run the SQL query?

– Josh
Mar 27 at 13:10





can you directly use OLEDB methods on your data source or paste your collections into excel run the SQL query?

– Josh
Mar 27 at 13:10













My datasource are DataTables. Can I use OLEDB without a database?

– Dirk Horsten
Mar 27 at 13:46






My datasource are DataTables. Can I use OLEDB without a database?

– Dirk Horsten
Mar 27 at 13:46











1 Answer
1






active

oldest

votes


















1














If I understood your question correct, you want a SQL syntax like multi-purpose select for data tables.



Based on the info found here: https://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx, I wrote the following example further down. You can expand it as you see fit.



TL;DR Add the System.Linq.Dynamic NuGet package so you can use strings for where clauses amongst others.



BTW: Writing a query string parser, to parse for instance "select category, sum(unit_price * units) as total_price from invoice group by category;" is entirely possible, but IMHO you will spend a lot of time to gain little.



using System.Data;
using System.Linq;
using System.Linq.Dynamic;

namespace Foo
public class Bar
/// <summary>
///
/// </summary>
/// <param name="from"></param>
/// <param name="where"></param>
/// <param name="skipRows"></param>
/// <param name="takeRows"></param>
/// <param name="orderBy">Needed for range selections (skipRows, takeRows) </param>
/// <returns></returns>
public DataTable GeneralPurposeSelect(DataTable from, string where = null, int? skipRows = null, int? takeRows = null, string orderBy = "Id")
var fromQryAble = from.AsEnumerable().AsQueryable();

IQueryable<DataRow> toQryAble = null;
if (!string.IsNullOrEmpty(where))
toQryAble = fromQryAble.Where(where);

if (takeRows != null)
if (skipRows == null)
skipRows = 0;


if (skipRows != 0)
if (takeRows == null)
takeRows = int.MaxValue;


if (takeRows != null)
if (skipRows == null)
skipRows = 0;

toQryAble = toQryAble == null ?
fromQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value) :
toQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value);


return toQryAble == null ? from : toQryAble.CopyToDataTable();








share|improve this answer


















  • 1





    Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

    – Dirk Horsten
    Mar 27 at 12:00










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55341461%2fhow-to-apply-a-sql-statement-on-one-or-more-datatables%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














If I understood your question correct, you want a SQL syntax like multi-purpose select for data tables.



Based on the info found here: https://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx, I wrote the following example further down. You can expand it as you see fit.



TL;DR Add the System.Linq.Dynamic NuGet package so you can use strings for where clauses amongst others.



BTW: Writing a query string parser, to parse for instance "select category, sum(unit_price * units) as total_price from invoice group by category;" is entirely possible, but IMHO you will spend a lot of time to gain little.



using System.Data;
using System.Linq;
using System.Linq.Dynamic;

namespace Foo
public class Bar
/// <summary>
///
/// </summary>
/// <param name="from"></param>
/// <param name="where"></param>
/// <param name="skipRows"></param>
/// <param name="takeRows"></param>
/// <param name="orderBy">Needed for range selections (skipRows, takeRows) </param>
/// <returns></returns>
public DataTable GeneralPurposeSelect(DataTable from, string where = null, int? skipRows = null, int? takeRows = null, string orderBy = "Id")
var fromQryAble = from.AsEnumerable().AsQueryable();

IQueryable<DataRow> toQryAble = null;
if (!string.IsNullOrEmpty(where))
toQryAble = fromQryAble.Where(where);

if (takeRows != null)
if (skipRows == null)
skipRows = 0;


if (skipRows != 0)
if (takeRows == null)
takeRows = int.MaxValue;


if (takeRows != null)
if (skipRows == null)
skipRows = 0;

toQryAble = toQryAble == null ?
fromQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value) :
toQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value);


return toQryAble == null ? from : toQryAble.CopyToDataTable();








share|improve this answer


















  • 1





    Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

    – Dirk Horsten
    Mar 27 at 12:00















1














If I understood your question correct, you want a SQL syntax like multi-purpose select for data tables.



Based on the info found here: https://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx, I wrote the following example further down. You can expand it as you see fit.



TL;DR Add the System.Linq.Dynamic NuGet package so you can use strings for where clauses amongst others.



BTW: Writing a query string parser, to parse for instance "select category, sum(unit_price * units) as total_price from invoice group by category;" is entirely possible, but IMHO you will spend a lot of time to gain little.



using System.Data;
using System.Linq;
using System.Linq.Dynamic;

namespace Foo
public class Bar
/// <summary>
///
/// </summary>
/// <param name="from"></param>
/// <param name="where"></param>
/// <param name="skipRows"></param>
/// <param name="takeRows"></param>
/// <param name="orderBy">Needed for range selections (skipRows, takeRows) </param>
/// <returns></returns>
public DataTable GeneralPurposeSelect(DataTable from, string where = null, int? skipRows = null, int? takeRows = null, string orderBy = "Id")
var fromQryAble = from.AsEnumerable().AsQueryable();

IQueryable<DataRow> toQryAble = null;
if (!string.IsNullOrEmpty(where))
toQryAble = fromQryAble.Where(where);

if (takeRows != null)
if (skipRows == null)
skipRows = 0;


if (skipRows != 0)
if (takeRows == null)
takeRows = int.MaxValue;


if (takeRows != null)
if (skipRows == null)
skipRows = 0;

toQryAble = toQryAble == null ?
fromQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value) :
toQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value);


return toQryAble == null ? from : toQryAble.CopyToDataTable();








share|improve this answer


















  • 1





    Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

    – Dirk Horsten
    Mar 27 at 12:00













1












1








1







If I understood your question correct, you want a SQL syntax like multi-purpose select for data tables.



Based on the info found here: https://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx, I wrote the following example further down. You can expand it as you see fit.



TL;DR Add the System.Linq.Dynamic NuGet package so you can use strings for where clauses amongst others.



BTW: Writing a query string parser, to parse for instance "select category, sum(unit_price * units) as total_price from invoice group by category;" is entirely possible, but IMHO you will spend a lot of time to gain little.



using System.Data;
using System.Linq;
using System.Linq.Dynamic;

namespace Foo
public class Bar
/// <summary>
///
/// </summary>
/// <param name="from"></param>
/// <param name="where"></param>
/// <param name="skipRows"></param>
/// <param name="takeRows"></param>
/// <param name="orderBy">Needed for range selections (skipRows, takeRows) </param>
/// <returns></returns>
public DataTable GeneralPurposeSelect(DataTable from, string where = null, int? skipRows = null, int? takeRows = null, string orderBy = "Id")
var fromQryAble = from.AsEnumerable().AsQueryable();

IQueryable<DataRow> toQryAble = null;
if (!string.IsNullOrEmpty(where))
toQryAble = fromQryAble.Where(where);

if (takeRows != null)
if (skipRows == null)
skipRows = 0;


if (skipRows != 0)
if (takeRows == null)
takeRows = int.MaxValue;


if (takeRows != null)
if (skipRows == null)
skipRows = 0;

toQryAble = toQryAble == null ?
fromQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value) :
toQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value);


return toQryAble == null ? from : toQryAble.CopyToDataTable();








share|improve this answer













If I understood your question correct, you want a SQL syntax like multi-purpose select for data tables.



Based on the info found here: https://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx, I wrote the following example further down. You can expand it as you see fit.



TL;DR Add the System.Linq.Dynamic NuGet package so you can use strings for where clauses amongst others.



BTW: Writing a query string parser, to parse for instance "select category, sum(unit_price * units) as total_price from invoice group by category;" is entirely possible, but IMHO you will spend a lot of time to gain little.



using System.Data;
using System.Linq;
using System.Linq.Dynamic;

namespace Foo
public class Bar
/// <summary>
///
/// </summary>
/// <param name="from"></param>
/// <param name="where"></param>
/// <param name="skipRows"></param>
/// <param name="takeRows"></param>
/// <param name="orderBy">Needed for range selections (skipRows, takeRows) </param>
/// <returns></returns>
public DataTable GeneralPurposeSelect(DataTable from, string where = null, int? skipRows = null, int? takeRows = null, string orderBy = "Id")
var fromQryAble = from.AsEnumerable().AsQueryable();

IQueryable<DataRow> toQryAble = null;
if (!string.IsNullOrEmpty(where))
toQryAble = fromQryAble.Where(where);

if (takeRows != null)
if (skipRows == null)
skipRows = 0;


if (skipRows != 0)
if (takeRows == null)
takeRows = int.MaxValue;


if (takeRows != null)
if (skipRows == null)
skipRows = 0;

toQryAble = toQryAble == null ?
fromQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value) :
toQryAble.OrderBy(orderBy).Skip(skipRows.Value).Take(takeRows.Value);


return toQryAble == null ? from : toQryAble.CopyToDataTable();









share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 9:22









Dieter VandroemmeDieter Vandroemme

211 bronze badge




211 bronze badge







  • 1





    Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

    – Dirk Horsten
    Mar 27 at 12:00












  • 1





    Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

    – Dirk Horsten
    Mar 27 at 12:00







1




1





Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

– Dirk Horsten
Mar 27 at 12:00





Thanks for proposing the IQueryable interface, which apparently has a GroupBy method : stackoverflow.com/questions/16522645/linq-groupby-sum-and-count/…. Though very usefull, it does not enable me to develop the general purpose function/action I hope to create. Looking forward to other answers.

– Dirk Horsten
Mar 27 at 12:00






Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55341461%2fhow-to-apply-a-sql-statement-on-one-or-more-datatables%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현