将 Linq 查询结果转换为字典 [英] Convert Linq Query Result to Dictionary

查看:36
本文介绍了将 Linq 查询结果转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Linq to SQL 向数据库添加一些行,但我想在添加行之前进行自定义检查",以了解是否必须添加、替换或忽略传入的行.我希望尽可能降低客户端和数据库服务器之间的流量,并尽量减少查询次数.

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. 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))
    )

最后我想要的是一个字典,而不必从 TableObject 下载整个 ObjectType 对象.

What I'd like to have at the end would be a Dictionary, without having to download the whole ObjectType objects from TableObject.

我也考虑过下面的代码,但我试图找到一个合适的方法:

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]);
}

推荐答案

尝试使用 ToDictionary 方法如下:

Try using the ToDictionary method like so:

var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );

这篇关于将 Linq 查询结果转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆