linq,选择列为IEnumerable <datarow> </datarow>

时间:2010-04-20 08:50:15

标签: c# .net linq ado.net

我怎么能在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")}  ;

这不起作用。我试图选择一些列作为新数据表,然后将其与其他数据表连接起来。

1 个答案:

答案 0 :(得分:10)

您可以使用http://code.msdn.microsoft.com/LinqEntityDataReader 然后选择你喜欢的值:

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();

一个更简单的解决方案,不需要外部库,就是创建一个DataTable(如果你还没有),并按如下方式填充它:

// 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