将 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章