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