2017-05-12 46 views
1

將空值添加到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" 
    } 
    ] 
} 
+1

你不能這樣做,因爲你的密鑰的類型爲'int'的,它不能有'null'值。一般來說,聽起來,從非空數據庫值返回'null'聽起來像一個壞主意,並導致數據對象和數據庫類型不匹配。也許,最好是檢查一下你是否真的需要這個,或者如果你能以另一種方式做到這一點。 –

回答

4

您可以修改您的關鍵參數類型爲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; 
} 
+0

我剛剛發佈了與您的解決方案非常相似的解決方案,因此我會接受您的答案。謝謝! –

+0

太棒了!不用謝! –

+0

一個建議:使用LINQ'Aggregate'方法重載提供一個'new List {new KeyValuePair (null,selectValue)});'作爲種子值爲 。這應該可以避免您插入列表頭部。 –

0

隨着大家的幫助下,我成功地實現它。這是迄今爲止我所得到的解決方案。

  1. 將int轉換爲int?接受null。
  2. 將Dapper結果轉換爲.ToList()
  3. 手動將對象行插入到List,其值爲空值和常量。

代碼:

public static IEnumerable<KeyValuePair<int?, string>> KeyValueList() 
{ 
    const string selectValue = "Select"; 
    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(); 

    result.Insert(0, new KeyValuePair<int?, string>(null, selectValue)); 

    return result; 
}