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

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

问题描述

我要添加一些行使用LINQ to SQL数据库,但我想添加的行知道我必须补充,更换或忽略进来的行之前做一个自定义检查。
我想保持在客户端和DB服务器之间的TRAFIC尽可能低和最小化查询的数量。

要做到这一点,我想取为在过程的开始要求验证,只有一次尽可能少的信息。

我在想这样做这样的事情的,但很明显,这是行不通的。任何人都有一个想法?

 词典< INT,日期> existingItems =
    (从TableObj OBJTYPE OT
        选择(新KeyValuePair< INT,日期>(ot.Key,ot.TimeStamp))
    )

想什么我有在末端将是一个字典,而不必从TableObject下载整个对象类型的对象。

我也考虑了以下code,但我试图找到一种合适的方式:

 列表< INT>键=(从OBJTYPE OT在TableObj排序依据ot.Key选择ot.Key).ToList< INT>();
清单<&日期时间GT;值=(从OBJTYPE OT在TableObj排序依据ot.Key选择ot.Value).ToList< INT>();
字典< INT,日期> existingItems =新词典< INT,日期>(keys.Count);
的for(int i = 0; I< keys.Count;我++)
{
    existingItems.Add(键[I],数值[I]);
}


解决方案

尝试使用的 ToDictionary 方法像这样:

  VAR字典= TableObj.Select(T =>新建{t.Key,t.TimeStamp})
                   .ToDictionary(T => t.Key,T => t.TimeStamp);

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

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

解决方案

Try using the ToDictionary method like so:

var dict = TableObj.Select( t => new { t.Key, t.TimeStamp } )
                   .ToDictionary( t => t.Key, t => t.TimeStamp );

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

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