Return Linq query to KeyValuePair key list

I am in the process of converting my application chart from predefined data to a database.

I used to use 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 here is what I am 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 error code is:

list = query; 

With an 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 the conversion?

+4
source share
1 answer

If you need a keyvaluepair list, you need to build it using keyvaluepairs! replace your anonymous object in the selected form:

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

Edited for 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();
+16
source

All Articles