Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Convert LINQ to DataTable Results

I would like to write a query that rather than say .Tolist () in Linq & Lambda output of the DataTable back, please help Me

For example, the following code

C#
var query = db.TblUsers.where (x => x.id! = 0) .Tolist ();


The output of the code above will generate a DataTable and use the same method Linq & lambda

below code writen by foreach but remove foreach by help linq & lambda

C#
var query = db.TblUsers.Where(x => x.Id != 0).ToList();
DataTable DT = new DataTable();
DT.Clear();
DT.Columns.Add("نام");
DT.Columns.Add("نام خانوادگی");
 
foreach (var item in query)
{
       Object[] O = { item.Name,item.Family };
       DT.Rows.Add(O);
}
 
dataGridView1.DataSource = DT



Regards
Yarian
Posted
Updated 9-Aug-16 4:51am
v2
Comments
Karthik_Mahalingam 9-Aug-16 1:49am    
misaqyrn9677 9-Aug-16 4:03am    
i dont want use foreach

1 solution

try this

C#
DataTable DT = new DataTable();
DT.Clear();
DT.Columns.Add("نام");
DT.Columns.Add("نام خانوادگی");


DataTable dtNew  = db.TblUsers.Where(x => x.Id != 0).Select(k => { var row = DT.NewRow(); row.ItemArray = new object[] { k.Name, k.Family }; return row; }).CopyToDataTable();
 
Share this answer
 
v2
Comments
[no name] 9-Aug-16 5:11am    
But DataTable has no method Where... or do I miss something?
Karthik_Mahalingam 9-Aug-16 5:12am    
TblUsers is a List < class >
[no name] 9-Aug-16 5:13am    
Ok, thank you :)
Karthik_Mahalingam 9-Aug-16 5:14am    
:)
misaqyrn9677 9-Aug-16 6:10am    
Below Error When Use It In Visual Studio 2012
A lambda expression with a statement body cannot be converted to an expression tree

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900