簡體   English   中英

如何使用Linq在列表中使用我的條件查詢DataTable?

[英]How do I query a DataTable using Linq with my criteria in a list?

我有一個DataTable其中包含從數據庫獲取的ID的列表。 我需要做的是獲取List<Of Integer>

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

我知道如何執行Linq To DataSet查詢,但是我不確定是否可以根據另一個List對其進行過濾,這是一些偽代碼來說明我要實現的目標:

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

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

有沒有一種簡單的方法可以執行此操作,而不必枚舉列表並檢查每個列表?

最有效的方法是使用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

有沒有一種方法可以進行此連接,從而使我不在列表中?

是的,那將是一個外部聯接 但是在這種情況下, Except更容易(甚至可能更有效):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM