2012-09-19 36 views
0

我有一個DataTable包含我從數據庫中獲得的Id列表。我需要做的是獲得List<Of Integer>如何使用Linq和列表中的條件查詢DataTable?

這個整數列表將是DataTable中的Id,但我需要根據另一個List<Of Integers>對它們進行過濾。所以我基本上試圖從DataTable生成一個Id列表,但前提是它們存在於我的另一個Id列表中。

我知道該怎麼做了Linq到數據集查詢,但我只是不知道是否有可能基於另一個列表過濾它,這裏的一些僞代碼來解釋我努力實現:

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

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

有沒有一種簡單的方法來做到這一點,而不必通過列表枚舉並檢查每一個?

回答

1

most efficient使用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 

糟糕!下面是VB.NET:

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

有沒有辦法做到這一點加入哪個會給我的Id不是列表中?

是的,那將是一個outer join。但是,在這種情況下Except更容易(甚至可能更有效):

Dim dbIDs = DBTable.AsEnumerable().Select(Function(r) r.Field(Of Int32)("Id")) 
Dim notInList As IEnumerable(Of Int32) = dbIDs.Except(ExistingList) 
+0

添喜的是有沒有辦法做到這一點加入哪個會給我的Id不是列表中? –

+0

是的,那將是[外部連接](http://msdn.microsoft.com/en-us/library/bb397895.aspx)。但在這種情況下,「Except」更容易(也可能更有效)。我很快會編輯我的答案。 –