將空值添加到IEnumerable中的最佳方式以下代碼返回List
作爲Key-Value Pair,該值在Database using Dapper中可用。 KeyValue對正在從WebApi控制器中調用並作爲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'的,它不能有'null'值。一般來說,聽起來,從非空數據庫值返回'null'聽起來像一個壞主意,並導致數據對象和數據庫類型不匹配。也許,最好是檢查一下你是否真的需要這個,或者如果你能以另一種方式做到這一點。 –