views:

100

answers:

1

I have a DataTable containing some records. Based on some conditions I have to filter records into two datatables.

Say

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

How to do this in LINQ for a DataTable that contains all the records?

A: 

LINQ is a query language that is meant for read operations. You can't do an insert operation in a LINQ query. What you can do is create three LINQ queries and iterate over them separately:

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


Update:

Or when you can do do it in a single LINQ statement, you can do this:

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;
    }
}

Update: Another option:

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);
}
Steven
@Steven: So does it mean, We Cannot do whole process in single Linq Statement in any way ?
Shantanu Gupta
@Shantanu: Yes you can write a single LINQ statement. See my update.
Steven
@Steven: this is not the one that i was expecting. This could have been done without using linq as well I think.
Shantanu Gupta
@Shantanu: Of course you can do this without LINQ. In fact, there is nothing you cannot do without LINQ :-). Please keep in mind that LINQ is for reading and transforming data, not for mutating data. While, in theory, it is possible to abuse LINQ to do the writing in the query, this is not advised, because than you are creating side effects in your query. Other developers simply don't effect a LINQ query to have side effects. So you need to iterate the list when you want to insert them into a DataTable.
Steven