我正在將我的圖表應用程序從預設數據轉換爲使用數據庫。將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>>'
如何實現轉換?
是否'新{x.IMEI,x.TimeTaken}'看起來像一個KeyValuePair給你? – 2014-08-28 16:33:18
來自另一篇文章:「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