Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq, selecting columns as IEnumerable<DataRow>

how can i do in linq:

IEnumerable<DataRow> query = 
        from rec in dt.AsEnumerable() 
        where rec.Field<decimal>("column2") == 1 && foo(rec.Field<decimal>("column1"))
        select new {
            column1 = rec.Field<decimal>("column1"),
            column2 = rec.Field<decimal>("column2"),
            column3 = rec.Field<decimal>("column3")}  ;

this does not work. Im trying to select some columns as new datatable then join it later with some other datatable.

like image 299
joe Avatar asked Dec 28 '22 19:12

joe


1 Answers

You can use http://code.msdn.microsoft.com/LinqEntityDataReader and then select your values like this:

DataTable query = 
        (from rec in dt.AsEnumerable() 
        where rec.Field<decimal>("column2") == 1 && foo(rec.Field<decimal>("column1"))
        select new {
            column1 = rec.Field<decimal>("column1"),
            column2 = rec.Field<decimal>("column2"),
            column3 = rec.Field<decimal>("column3")}).ToDataTable();

A much more simple solution, that doesn't require external libraries, would be to create a DataTable (if you don't already have one), and populate it as follows:

// declaring a data table.. Replace it with whatever code you want
var table = new DataTable();
table.Columns.Add("column1", typeof(Decimal));
table.Columns.Add("column2", typeof(Decimal));
table.Columns.Add("column3", typeof(Decimal));

// Populate the table
(from rec in dt.AsEnumerable() 
where rec.Field<decimal>("column2") == 1 && foo(rec.Field<decimal>("column1"))
select new {
    column1 = rec.Field<decimal>("column1"),
    column2 = rec.Field<decimal>("column2"),
    column3 = rec.Field<decimal>("column3")})
    .Aggregate(table, (dt, r) => { dt.Rows.Add(r.column1, r.column2, r.column3); return dt; });

// at this point your table variable is populated
like image 87
Artiom Chilaru Avatar answered Dec 31 '22 14:12

Artiom Chilaru