gpt4 book ai didi

c# - 通过示例将空值添加到 IEnumerable 作为第一记录的最佳方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:34 33 4
gpt4 key购买 nike

以下代码使用 Dapper 返回数据库中可用的 List 作为键值对。 KeyValue 对从 WebApi Controller 调用并作为 Json 提供,因此 Javascript 脚本可以将该列表用于下拉框。

public static IEnumerable<KeyValuePair<int, string>> KeyValueList()
{
const string sql = @"SELECT Key ,
Value
FROM Constants";
var result = DataStoreReader.Query(ConnectionHelper.GetConnectionString, sql)
.Select(item =>
new KeyValuePair<int, string>(item.Key, item.Value));

return result;
}

以上代码以Json形式返回如下结果。

{
"results": [
{
"key": 1,
"value": "Value - 1"
},
{
"key": 2,
"value": "Value - 2"
}
]
}

但是,我需要这个结果,请注意第一个对象 null 必须自动添加。但是,我的数据库没有空记录,无法添加

{
"results": [
{
"key": null,
"value": "Select"
},
{
"key": 1,
"value": "Value - 1"
},
{
"key": 2,
"value": "Value - 2"
}
]
}

最佳答案

您可以将您的关键参数类型修改为int?,并且:

public static IEnumerable<KeyValuePair<int?, string>> KeyValueList()
{
const string sql = @"SELECT Key ,
Value
FROM Constants";
var result = DataStoreReader.Query(ConnectionHelper.GetConnectionString, sql)
.Select(item => new KeyValuePair<int?, string>(item.Key, item.Value))
.ToList();
//Insert the first/default element
result.Insert(0, new KeyValuePair<int?, string>(null, "Select"));

return result;
}

关于c# - 通过示例将空值添加到 IEnumerable 作为第一记录的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43928811/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com