2
votes

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

1 Answers

3
votes

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