如何在LINQ To DataSet中使用案例条件

时间:2010-08-24 09:47:06

标签: linq datatable dataset linq-to-objects

我有一个包含一些记录的DataTable。基于某些条件,我必须将记录过滤成两个数据表。

When row["ItemType"]==1
     //Insert item into DataTable 1
When row["ItemType"]==2
     //Insert item into DataTable 2
Else
     //Insert item into DataTable 3

如何在LINQ中为包含所有记录的DataTable执行此操作?

1 个答案:

答案 0 :(得分:0)

LINQ是一种用于读取操作的查询语言。您不能在LINQ查询中执行插入操作。你可以做的是创建三个LINQ查询并分别迭代它们:

var rows1 = from row in rows where row["ItemType"] == 1 select row;
var rows2 = from row in rows where row["ItemType"] == 2 select row;
var rows3 = from row in rows where row["ItemType"] == 3 select row;

foreach (var row in rows1) { /* Insert item into DataTable1 */ }
foreach (var row in rows2) { /* Insert item into DataTable2 */ }
foreach (var row in rows3) { /* Insert item into DataTable3 */ }

<小时/> 更新:

或者当您可以在单个LINQ语句中执行此操作时,可以执行以下操作:

var rows =
    from row in rows 
    select new { Row = row, Item =  row["ItemType"] };

foreach (var row in rows)
{
    switch (row.Item)
    {
        case 1:
            // Insert item into DataTable1
            break;
        case 2:
            // Insert item into DataTable2
            break;
        case 3:
            // Insert item into DataTable3
            break;
    }
}

更新:另一种选择:

var rows =
    from row in rows
    select new
    {
        Row = row, 
        Table = row["ItemType"] == 1 ? table1 : 
            (row["ItemType"] == 2 ? table2 : table3)
    };

foreach (var row in rows)
{
    var table = row.Table;
    var row = row.Row;

    table.Rows.Add(row);
}