2014-08-28 59 views
4

我正在將我的圖表應用程序從預設數據轉換爲使用數據庫。將Linq查詢返回到KeyValuePair的列表中

以前我用的是這樣的:

var data = new Dictionary<string, double>();    

switch (graphselected) 
{   
case "1": 
    data = new Dictionary<string, double> 
    { 
     {"Dave", 10.023f}, 
     {"James", 20.020f}, 
     {"Neil", 19.203f}, 
     {"Andrew", 4.039f}, 
     {"Steve", 5.343f} 
    }; 
    break; 
case "2": 
    data = new Dictionary<string, double> 
    { 
     {"Dog", 10.023f}, 
     {"Cat", 20.020f}, 
     {"Owl", 19.203f}, 
     {"Rat", 16.039f}, 
     {"Bat", 27.343f} 
    }; 
    break; 
//etc... 
} 

// Add each item in data in a foreach loop 
foreach (var item in list) 
{ 
    // Adjust the Chart Series values used for X + Y 
    seriesDetail.Points.AddXY(item.Key, item.Value); 
} 

這就是我想要做的事:

var list = new List<KeyValuePair<string, double>>(); 

switch (graphselected) 
{ 
case "1": 
    var query = (from x in db2.cd_CleardownCore 
       where x.TimeTaken >= 10.0 
       select new { x.IMEI, x.TimeTaken }).ToList(); 
    list = query;     
    break; 
//... 
} 

我的代碼錯誤對:

list = query; 

,出現錯誤:

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' 
to 'System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string,double>>' 

如何實現轉換?

+5

是否'新{x.IMEI,x.TimeTaken}'看起來像一個KeyValuePair給你? – 2014-08-28 16:33:18

+0

來自另一篇文章:「LINQ需要一個無參數的構造函數,因爲它想使用集合初始化({}括號)。你可以有額外的類構造函數,但是LINQ不會使用它們。據我瞭解,這是爲什麼它的格式與我的代碼一樣。來自:http://stackoverflow.com/questions/15382840/only-parameterless-constructors-and-initializers-are-supported-in-linq-to-entiti – Baggerz 2014-08-29 08:53:28

回答

16

如果你想要一個keyvaluepair列表,你需要很好地構建它,keyvaluepairs!在選擇這樣替換你匿名對象:

select new KeyValuePair<string,double>(x.IMEI,x.TimeTaken) 

編輯爲您的新問題:

var q = (from x in db2.cd_CleardownCore 
      where x.TimeTaken >= 10.0 
      select new { x.IMEI, x.TimeTaken }); 
var query = q.AsEnumerable() // anything past this is done outside of sql server 
     .Select(item=>new KeyValuePair<string,double?>(item.IMEI,item.TimeTaken)) 
     .ToList(); 
+1

你好羅南,謝謝你的幫助,我試着用上面的代碼但由於我的雙倍可空我得到: 參數2:不能從'雙?'轉換嗎?到'雙' 我試着改變它爲 選擇新的KeyValuePair <字符串,雙>(x.IMEI,(雙)x.TimeTaken))。ToList(); 但現在給出了以下錯誤: 只有無參數的構造函數和初始化器在LINQ to Entities中受支持。 – Baggerz 2014-08-29 08:09:59

+0

如果你的值可以爲空,那麼無論如何只要使用我給出的代碼就可以了,只需使用我給你的代碼,而改變你的「list」變量的類型以便兼容,就像var list = new List >()?; – 2014-08-29 08:25:20

+0

感謝ronan,我嘗試了上面的,但它不喜歡在選擇新的KeyValuePair <字符串,雙>(x.IMEI,x.TimeTaken)012雙重(所以我改變它選擇新的KeyValuePair <字符串,雙?>(十。 IMEI,x.TimeTaken) 但是,當代碼運行時,我得到了同樣的錯誤:LINQ to Entities只支持無參數的構造函數和初始值設定項。 – Baggerz 2014-08-29 08:43:07