將 Linq 查詢結果轉換爲字典 - Convert Linq Query Result to Dictionary

問題:

I want to add some rows to a database using Linq to SQL, but I want to make a "custom check" before adding the rows to know if I must add, replace or ignore the incomming rows.我想使用 Linq to SQL 向數據庫添加一些行,但我想在添加行之前進行“自定義檢查”,以瞭解是否必須添加、替換或忽略傳入的行。 I'd like to keep the trafic between the client and the DB server as low as possible and minimize the number of queries.我想保持客戶端和數據庫服務器之間的流量儘可能低,並儘量減少查詢次數。

To do this, I want to fetch as little information as required for the validation, and only once at the beginning of the process.爲此,我希望獲取驗證所需的儘可能少的信息,並且僅在流程開始時獲取一次。

I was thinking of doing something like this, but obviously, it doesn't work.我正在考慮做這樣的事情,但顯然,它不起作用。 Anyone have an idea?有人有想法嗎?

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj
        select (new KeyValuePair<int, DateTime>(ot.Key, ot.TimeStamp))
    )

What I'd like to have at the end would be a Dictionary, without having to download the whole ObjectType objects from TableObject.最後我想要的是一個字典,而不必從 TableObject 下載整個 ObjectType 對象。

I also considered the following code, but I was trying to find a proper way:我還考慮了以下代碼,但我試圖找到一種正確的方法:

List<int> keys = (from ObjType ot in TableObj orderby ot.Key select ot.Key).ToList<int>();
List<DateTime> values = (from ObjType ot in TableObj orderby ot.Key select ot.Value).ToList<int>();
Dictionary<int, DateTime> existingItems = new Dictionary<int, DateTime>(keys.Count);
for (int i = 0; i < keys.Count; i++)
{
    existingItems.Add(keys[i], values[i]);
}

解決方案:

參考一: https://stackoom.com/question/409n
參考二: Convert Linq Query Result to Dictionary
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章