0

I have a DataTable containing a list of Id's I get from the DB. What I need to do is get a List<Of Integer>.

This list of integers will be the Id's in the DataTable, but I need to filter them based on another List<Of Integers>. So I'm basically trying to generate a list of Id's from the DataTable but only if they exist in my other list of Ids.

I know how to do the Linq To DataSet query, but I'm just not sure if it's possible to filter it based on another List, here's some pseudo code to explain what I'm trying to achieve:

List<Of Integer> ExistingList = GetReferenceIds(whatever)
DataTable DBTable = GetAllDatabaseIds(whatever)

List<Of Integer> FilteredList = DBTable.AsEnumerable()
                                    .Where(Column("Id") IN FilteredList).ToList()

Is there an easy way to do this without having to enumerate through the list and check each one?

cuongle
  • 74,024
  • 28
  • 151
  • 206
Daniel Minnaar
  • 5,865
  • 5
  • 31
  • 52

1 Answers1

2

The most efficient is using Enumerable.Join:

IEnumerable<int> IDs = from row in DBTable.AsEnumerable()
             join id in ExistingList
             on row.Field<int>("Id") equals id 
             select id;  // selects the id, you could also select the DataRow

Oops! Here's VB.NET:

Dim IDs = From row In DBTable
          Join id In ExistingList
          On row.Field(Of Int32)("Id") Equals id
          Select id

Is there a way to do this join which would give me the Id's NOT in the list?

Yes, that would be an outer join. But in this case Except is easier (and probably even more efficient):

Dim dbIDs = DBTable.AsEnumerable().Select(Function(r) r.Field(Of Int32)("Id"))
Dim notInList As IEnumerable(Of Int32) = dbIDs.Except(ExistingList)
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Hi Tim, is there a way to do this join which would give me the Id's NOT in the list? – Daniel Minnaar Sep 19 '12 at 08:39
  • Yes, that would be an [outer join](http://msdn.microsoft.com/en-us/library/bb397895.aspx). But in this case `Except` is easier (and probably more efficient). I'll edit my answer soon. – Tim Schmelter Sep 19 '12 at 08:41