tags:

views:

166

answers:

1

Hi,

I am attempting to use Linq to project each row from a DB query into a dictionary that has a custom type as its value. I am unsure of the LINQ syntax to do this?

This is my current attempt (which doesn't compile, but should demonstrate what I am trying to do). I am having trouble with the 'select new...' part.

public class MyClass
{     
   public Dictionary<int, CustomType> dict;
}

public class MyType{        
   string Name;
   decimal Value;
}

var result = (from t in table
              select new {
                 t.Id,
                 new MyType(t.Name,t.Value)
              }).AsEnumerable().ToDictionary();

ANSWER:

Thanks Jason. I just used properties and automatic initialisers rather than a constructor. The working code resembles this (any improvements to this are welcome):

public class MyType {        
    public string Name {get;set;}
    public decimal Value { get; set;}
}

Dictionary<int, CustomType> dict;

dict = (from t in table
        select new {
           id = av.Account.Id,
           mt = new MyType { Name = t.Name, Value = t.Value }
        }).ToDictionary(item => item.id, item => item.mt);
+5  A: 

MyType doesn't have a constructor that takes two arguments.

Add the following to the definition of MyType:

public MyType(string name, decimal value) {
    Name = name; 
    Value = value;
}

Further, you did not give the anonymous type member defined by

new MyType(t.Name, t.Value)

a name; try changing that line to:

MyType = new MyType(t.Name, t.Value)

The compiler will yell at you that it can not discern a name for this anonymous member.

Finally, there isn't an overload of ToDictionary that has no arguments. Assuming you named the above anonymous member to be MyType, change the call to ToDictionary to be

....ToDictionary(item => item.Id, item => item.MyType);
Jason