【发布时间】:2020-04-08 18:17:02
【问题描述】:
我有一些脚本,它首先检查数据库中是否有一些值,然后根据这些值创建新集合。我不知道这个结果是否是我无法得到的最好结果,我认为没有。如果有人可以帮助我,我将不胜感激
var tempDict = request.Number_Name
.Where(k => _context.Users.Where(x => x.Status == 0).Select(x => x.Phone).Contains(k.Key) || _context.Users.Where(x => x.Status == 0).Select(x => x.PhoneWithoutCC).Contains(k.Key))
.ToDictionary(k => k.Key, v => v.Value);
var finalDict = new Dictionary<string, string>();
foreach (var kv in tempDict)
{
var number = _context.Users.Where(x => x.Status == 0).Where(x => kv.Key == x.PhoneWithoutCC || kv.Key == x.Phone).Select(x => new { x.Phone, x.DisplayName }).FirstOrDefault();
if (!kv.Key.Contains("+"))
{
finalDict[number.Phone] = number.DisplayName;
}
else
{
finalDict[kv.Key] = number.DisplayName;
}
}
【问题讨论】:
-
如果您使用延迟加载“_context.Users.Where(x => x.Status == 0)”,每次您尝试使用它时都会尝试连接数据库。
-
"finalDict[number.Phone] = number.DisplayName" 会引发空引用异常
-
这段代码会有可怕的表现。您确实需要最少访问数据库的次数。
标签: c# linq optimization