23

hi how i can filter a datatable with linq to datatable? I have a DropDownList and there I can select the value of the Modul Column. Now I want to filter the DataTable with this Modul Column.

here is my datatable structure:

User | Host | TimeDiff | License | Telefon | Modul 

Here the Code:

protected void drp_Modules_SelectedIndexChanged(object sender, EventArgs e)
{
    string value = drp_Modules.SelectedValue;

    DataTable tb = (DataTable)Session["dt_Users"];

    tb = from item in tb //?????

    LoadUsertable(tb);
}
4
  • 1
    please refer this msdn.microsoft.com/en-us/library/bb669073.aspx Commented Oct 18, 2013 at 12:18
  • Is it important to use LINQ ? Commented Oct 18, 2013 at 12:21
  • You can use the Select() method on the DataTable Commented Oct 18, 2013 at 12:22
  • 1
    see this for query DataTable with Linq Commented Oct 18, 2013 at 12:22

3 Answers 3

52

You are better of using DataTable.Select method, but if you have to use LINQ then you can try:

DataTable selectedTable = tb.AsEnumerable()
                            .Where(r => r.Field<string>("Modul") == value)
                            .CopyToDataTable();

This would create a new DataTable based on filtered values.

If you use DataTable.Select

string expression = "Modul =" + value;
DataRow[] selectedRows = tb.Select(expression);
Sign up to request clarification or add additional context in comments.

3 Comments

I know I'm a little late to the party for this one, but thanks, that helped quite a bit with something I'm working on.
@Habib, Just a simple comment. THANKS!!! I was breaking my head trying to cast the Rows, etc, etc, etc, when I found your answer.
stackoverflow.com/questions/35507109/… I have multiple columns or single column. How can I do either? Thanks.
3

You can use condition to check rows exist in addition before casting. System.Linq namespace is required for Any() to work

var rows = values.AsEnumerable().Where
            (row => row.Field<string>("Status") == action);//get the rows where the status is equal to action

if(rows.Any())
{
    DataTable dt = rows.CopyToDataTable<DataRow>();//Copying the rows into the DataTable as DataRow
}

Comments

1

To Retrieve the DataTable based on filtering the list of item.(i.e.,if any of the list item is present in datatable, that matched result will received.

 List<string>item=new List<string>(){"TG1","TG2"};     
 DataTable tbsplit = (from a in tbl.AsEnumerable()
              where item.Any(x => a.Field<string>("CSubset").ToUpper().Contains(x.ToUpper()))
              select a).CopyToDataTable();//By Executing this, the Filter DataTable is obtained

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.