将Linq查询结果转换为字典

Tip*_*ipx 327 c# linq todictionary linq-to-sql

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

为此,我希望获取验证所需的信息,并且只需要在流程开始时获取一次.

我在考虑做这样的事情,但很明显,它不起作用.有人有想法吗?

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

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

我还考虑了以下代码,但我试图找到一个正确的方法:

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]);
}
Run Code Online (Sandbox Code Playgroud)

tva*_*son 604

尝试使用如下ToDictionary方法:

var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );
Run Code Online (Sandbox Code Playgroud)

  • @BenCollins:我认为中间的`.Select`导致生成的SQL只选择Key和TimeStamp,而不是选择每一列. (9认同)
  • 如果您正在执行 Linq to Object(而不是 Linq to SQL),则可以省略此中间“Select” (5认同)
  • 为什么`.Select(t => new {t.Key,t.TimeStamp})`表达式是必要的? (3认同)
  • @pawan,它是枚举中每个元素的占位符,并采用枚举中对象的类型. (2认同)
  • 如果这对某人有帮助,我一直在 EF Core 5.0 的范围内寻找它。中间的“.Select”确实避免了从数据库中的实体模型/表中选择每一列。 (2认同)

BFr*_*ree 117

看看你的例子,我认为这就是你想要的:

var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
Run Code Online (Sandbox Code Playgroud)

  • 您可以这样做:TableObj.Select(t => new {t.Key,t.TimeStamp}).ToDictionary(t => t.Key,t => t.TimeStamp); LinqToSql应该能够注意到你只需要两件事(来自select)并返回它们.我不确定它是否足够聪明,可以深入研究ToDictionary()的细节. (7认同)

Jar*_*Par 7

请尝试以下方法

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);
Run Code Online (Sandbox Code Playgroud)

或完全成熟的类型推断版本

var existingItems = TableObj.ToDictionary(x => x.Key);
Run Code Online (Sandbox Code Playgroud)