2

i have a array list of unique Ids

ex 1,2,3,4....

and a DataTable with Records with the above IDs

ID    Name
1     abc
2     xxx
3     aaa
4     bbb
5     eee
6     fff

i need to filter the data table as per the array list content

ex: if array list contain 1,2

then the DataTable should be filtered only to contain those two records.is there any option on DataTable that i could do this other than running the DataTable inside For Loop and getting each DataRow?

1 Answer 1

3

You can use Linq to filter and potentially create a new DataTable.

var filtered = 
    table.AsEnumerable()
        .Where(r => list.Contains(r.Field<int>("ID")))
        .CopyToDataTable();

Given a list containing { 1, 2 }, the filtered table will contain the rows { { 1, "abc" }, { 2, "xxx" } }

Side note: While you can use ArrayLists, it is preferrable to use the generic counterpart System.Collections.Generic.List<T> in new code written in .NET. Generics were introduced as part of .NET 2.0 / C# 2.0 / VB 8 / Visual Studio 2005. The present editions on the market are .NET 4.0 / C# 4.0 / VB 10 / Visual Studio 2010. ArrayLists are effectively obsolete except in the case of supporting code originating in earlier versions of the langauge and framework.

Also, if the list is particularly large, it might be worth first loading it into a HashSet<T> prior to the query, as it will be more performant when using a Contains method.


Full working code demonstration:

var table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "abc");
table.Rows.Add(2, "xxx");
table.Rows.Add(3, "aaa");
table.Rows.Add(4, "bbb");
table.Rows.Add(5, "eee");
table.Rows.Add(6, "fff");

// var list = new ArrayList(); // do not prefer
var list = new List<int>();
list.Add(1);
list.Add(2);

var filtered =
    table.AsEnumerable()
        .Where(r => list.Contains(r.Field<int>("ID")))
        .CopyToDataTable();
Sign up to request clarification or add additional context in comments.

3 Comments

i'm getting the exception -"The source contains no DataRows." but still the DataTable Has the IDs in the ArrayList
That error will only occur if the source table has no rows or none of them pass the predicate in the where. So either your original table is empty, or it's not matching the values in your list. You will have to debug to verify. I am posting a full snippet of code to demonstrate the working behavior.
as you mentioned i started using the List<int> now it's working.according to above filtering method the DataTable filtering code requires exactly the integer items on the list.thanx for the help..

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.