2

I would like to return a list of keypairvalues from a linq query but when I do I get

Only parameterless constructors and initializers are supported in LINQ to Entities

I think this is because a KeyValuePair does not have a empty constructor but there has to be a way to return a list of keypairvalues in a linq statement maybe use .ToDictionary() or something ?

See my query below

{
    List<KeyValuePair<string, string>> sup;
    sup = (
        from s in db.LU_opcoVendor
            .GroupBy(x => x.supplierNumber)
            .Select(x => x.FirstOrDefault())
        join su in db.suppliers on s.supplierNumber equals su.supplierNumber
        select new KeyValuePair<string, string>(s.supplierNumber, su.supplierDesc))
        .ToList();
}
RB.
  • 36,301
  • 12
  • 91
  • 131
Micah Armantrout
  • 6,781
  • 4
  • 40
  • 66
  • In your linq to entities code use an anonymous type as the output and then add a select onto the chain outside of the Entities setup. – tolanj Jun 15 '16 at 16:02

1 Answers1

2

Here is one way to do it. You convert to an in memory list first and then execute the conversion to List<KeyValuePair<string, string>>.

List<KeyValuePair<string, string>> sup = (from s in db.LU_opcoVendor.GroupBy(x => x.supplierNumber).Select(x => x.FirstOrDefault())
   join su in db.suppliers on s.supplierNumber equals su.supplierNumber
   select new {s.supplierNumber, su.supplierDesc})
   .ToList() // materialize the list back from the data store to memory
   .Select(s => new KeyValuePair<string, string>(s.supplierNumber, s.supplierDesc)) // now you can use a constructor with parameters
   .ToList(); // convert the IEnumerable back to a List
Igor
  • 60,821
  • 10
  • 100
  • 175