How to Convert DataTable into List/Linq (using LamdaExpression / LINQ)

Posted by Abdul.Ha under C# on 7/27/2012 | Points: 10 | Views : 8660 | Status : [Member] | Replies : 1
How to Convert DataTable into List/Linq (using LamdaExpression / LINQ):
____________________________________________________________________
(1) var v = (from row in dt.AsEnumerable()
select new
{
Ques = row["Ques"].ToString(),
Answer = row["Answer"].ToString()
}).ToList();
//Note: If we dont write .Tolist() then also no problem.
(2)
var query = (from row in dtCount.AsEnumerable()
group row by new
{
Name = row.Field<String>("Name"),
FM_ID = row.Field<Int32>("ID")
} into grp
orderby grp.Sum(r => r.Field<Int32?>("TotalFiles")) descending
select new
{
TotalFiles = grp.Sum(r => r.Field<Int32?>("TotalFiles")),
Name = grp.Key.Name,
ID = grp.Key.ID
});
_________________________________________________________________________
//// How to Convert Linq/List into DataTable:
using System.Reflection; using System.Collections.Generic; using System.Linq;
public DataTable ConvertLinqIntoDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
//Column Names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;

if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
______________________________________________________________________________




Responses

Posted by: Vuyiswamb on: 7/27/2012 [Member] [MVP] [Administrator] NotApplicable | Points: 25

Up
0
Down
Always format your code in Code tags , its Difficult to read your code like this

Thank you for posting at Dotnetfunda
[Administrator]

Abdul.Ha, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response