2014-08-28 61 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