小编Sam*_*Sam的帖子

为什么迭代IQueryable会为结果中的每个项目提供第一个值?

我有一个代码块,试图从数据库中查询一些简单的配置参数.但是,使用下面的代码,只要我枚举结果,我就会得到结果中每个项目的第一个值:

var db = new ConfigurationServiceDataContext("Server=vsdcs022.aridev.lcl;Database=ConfigurationService;Trusted_Connection=True;");

var parameters =
    from configContents in db.ConfigurationContents
    where
        configContents.ConfigurationContextsTable.ConfigurationContextName == contextName &&
        configContents.ConfigurationSectionTable.ConfigurationSectionName == sectionName
    select configContents;

// print stuff for debugging purposes:
foreach (var parameter in parameters)
{
    Console.WriteLine("key = '{0}', value = '{1}'", parameter.ConfigurationKey, parameter.ConfigurationValue);
}

return parameters.ToDictionary(parameter => parameter.ConfigurationKey, parameter => parameter.ConfigurationValue);
Run Code Online (Sandbox Code Playgroud)

如果我打印结果(在尝试将它们添加到新词典之前),我会得到类似的结果:

key = 'key1', value = 'value1'
key = 'key1', value = 'value1'
key = 'key1', value = 'value1'
Run Code Online (Sandbox Code Playgroud)

但是,如果我用匿名类型替换选择行,它可以正常工作:

    select new { configContents.ConfigurationKey, configContents.ConfigurationValue };
Run Code Online (Sandbox Code Playgroud)

使用此匿名类型,我得到以下结果: …

.net c# linq-to-sql

8
推荐指数
1
解决办法
585
查看次数

标签 统计

.net ×1

c# ×1

linq-to-sql ×1