I\'m trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:
IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()
select myRow["server"].ToString() ;
Try this...
SqlCommand cmd = new SqlCommand( "Select * from Employee",con);
SqlDataReader dr = cmd.ExecuteReader( );
DataTable dt = new DataTable( "Employee" );
dt.Load( dr );
var Data = dt.AsEnumerable( );
var names = from emp in Data select emp.Field<String>( dt.Columns[1] );
foreach( var name in names )
{
Console.WriteLine( name );
}
var results = from myRow in myDataTable
where results.Field<Int32>("RowNo") == 1
select results;
//Json Formating code
//DT is DataTable
var filter = (from r1 in DT.AsEnumerable()
//Grouping by multiple columns
group r1 by new
{
EMPID = r1.Field<string>("EMPID"),
EMPNAME = r1.Field<string>("EMPNAME"),
} into g
//Selecting as new type
select new
{
EMPID = g.Key.EMPID,
MiddleName = g.Key.EMPNAME});
It's not that they were deliberately not allowed on DataTables, it's just that DataTables pre-date the IQueryable and generic IEnumerable constructs on which Linq queries can be performed.
Both interfaces require some sort type-safety validation. DataTables are not strongly typed. This is the same reason why people can't query against an ArrayList, for example.
For Linq to work you need to map your results against type-safe objects and query against that instead.
Try this
var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ;