Coder Absolute Coder Absolute - 7 months ago 27
C# Question

Best way to add null value to IEnumerable as First Record with an example

The following code returns the

List
as Key-Value Pair what is available in the Database using Dapper. The KeyValue Pair is being called from the WebApi Controller and being served as
Json
, so that list can be used by the Javascript script for a drop down box.

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;
}


The above code returns the following result as Json.

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


But, I need this result, notice the first object as
null
must be automatically added. However, my database doesn't have the null record and it is not possible to add.

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

Answer Source

You can modify your key parameter type to int?, and:

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;
}