Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Linq Query into a List of KeyValuePair's

I'm in the process of converting my chart application from preset data to using a database.

Previously I was using this:

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

And this is what I'm trying to do:

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;
//...
}

My code Error's on:

list = query; 

With Error :

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

How can I implement a conversion?

like image 892
Baggerz Avatar asked Aug 28 '14 16:08

Baggerz


1 Answers

If you want a list of keyvaluepair, you need to build it with well, keyvaluepairs! replace your Anonymous object in the select as such :

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

Edited for your new issues:

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();
like image 66
Ronan Thibaudau Avatar answered Nov 18 '22 21:11

Ronan Thibaudau