将Linq查询返回到KeyValuePair的列表中

时间:2014-08-28 16:31:19

标签: c# 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>>'

如何实施转化?

1 个答案:

答案 0 :(得分:18)

如果你想要一个keyvaluepair列表,你需要用keyvaluepairs来构建它!在select中替换你的Anonymous对象:

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();