1

I'm trying to convert a datatable to a dictionary using the method described here, but I get an error

Cannot implicitly convert type System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.Dictionary``.

This link helped, but only one value is pulled into the dictionary, not several which is what I need.

Thanks for any help.

public class MCEAV
{
    public int ID { get; set; }
    public int BOOK_ID { get; set; }
    public double DATA { get; set; }
}

Dictionary<int, MCEAV> dctGREEKS = new Dictionary<int, MCEAV>();
dctGREEKS = DATActx.MONTECARLO_EAVs.Select(Z => new { Z.ID, Z.BOOK_ID, Z.DATA}).ToDictionary(Z => Z.ID);
nvoigt
  • 75,013
  • 26
  • 93
  • 142
Zeus
  • 1,496
  • 2
  • 24
  • 53

2 Answers2

2

You need to specify the name of the class when using new else it is an anonymous type:

dctGREEKS = DATActx.MONTECARLO_EAVs.Select(Z => 
                               new MCEAV()
                               { 
                                  ID = Z.ID, 
                                  BOOK_ID = Z.BOOK_ID, 
                                  DATA = Z.DATA
                               }).ToDictionary(Z => Z.ID);

So new { Z.ID, Z.BOOK_ID, Z.DATA} is an instance of an anonymous type created by the compiler while new MCEAV() is an instance of type MCEAV which is what you want for your dictionary.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
2

Based on your code, I guess you want something like this.

var result = dt.AsEnumerable()
        .ToDictionary(x=>x.Field<int>("ID"), 
                      x=> new MCEAV() 
                      {
                          ID = x.Field<int>("ID"),
                          BOOK_ID = x.Field<int>("BOOK_ID"), 
                          DATA = x.Field<double>("DATA") 

                      });

Check this Example

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35