I want to make a generalized Data Table to Linq Collection
I am a beggginer so if it’s not possible please let me know
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select new {
Order = row["Order"].ToString(),
Something = row["Something"].ToString(),
Customer = row["Customer"].ToString(),
Address = row["Address"].ToString()
};
}
That is the code for one table
i want something like this:
public static void convertDatatable(DataTable dt)
{
var results = from myRow in dt.AsEnumerable()
select new
{
foreach(DataColumn column in dt.Columns)
column.ColumnName // linq Variable name
= myRow[column.ColumnName];// linq Variable Value
};
}
I know it doesn’t work how i wrote it but is there another way ?
Note: the reason i am doing this is because i can’t convert Datatable directly to JSON it serializes it to XMl then sends it as a string containing that xml.
If you want to stay with datatables then there is this, mentioned in another SO: What should I use to serialize a DataTable to JSON in ASP.NET 2.0?, which links to What should I use to serialize a DataTable to JSON in ASP.NET 2.0?.
I highly recommend, however, that you consider moving away from DataTables and DataRows, replacing it instead with an ORM such as Entity Framework (EF Quick Start here) or Linq to Sql – there are others, but since you are a beginner these offer the easiest learning curve; not least because of the full designer support in Visual Studio.
For the standard forms of JSON serialization offered by .Net (e.g. WCFs DataContractSerializer or the Asp.Net JSON serializer) then you need concrete types. The ORM solution will create all your table wrapper types at design-time, giving you a concrete type, potentially, for every table in your database.
As for the idea you’ve specifically outlined above, it is exceptionally difficult to achieve – because the compiler, in the first example, dynamically generates a type whose members match the names and types of the expressions you use. If you open your compiled code in ILSpy and switch to IL instead of C# you’ll see what I mean.
Therefore, to reproduce it dynamically you would need to dynamically emit a class, probably using
ILGenerator, doing the same thing; and then dynamically emit the expression tree (using theExpressionclass’ static factory methods) to fill it out; and finally compile and execute it.I would only look at doing something like that if I literally couldn’t do it any other way – I’d be more likely to just write a routine to iterate through each column and write the JSON to a
StringBuilderand return that! But if I could use an ORM, then I’d do that instead.