Trying to get a string concatenated in Linq2Entities query
I am trying to create a Dictionary<string, string>
from the combined results of two string f开发者_如何转开发ields in an entity.
I am using this dictionary to populate a drop down list. For this particular case, both the key and value are the same.
Here is the query I have so far:
var qry = (
from x in db.Treatment_Type
select new {
TreatmentCode = x.Project_Classification + ":" + x.Improvement_Type
})
.AsEnumerable()
.ToDictionary<string, string>(x => x);
I am trying to concatenate the Project_Classification
and Improvement_Type
values into one value. It is coming back as an anonymous type, instead of a string, so I get errors about how the dictionary can't infer the types from the anonymous type and advising me to explicitly state the type. When I do that, I get errors that anonymous types can't be converted to string.
How can I accomplish this?
Why don't you just get rid of it being an anonymous type? That's not helping you:
var qry = (from x in db.Treatment_Type
select x.Project_Classification + ":" + x.Improvement_Type)
.AsEnumerable()
.ToDictionary<string, string>(x => x);
Only use anonymous types when you actually get some benefit from it :)
The same applies to query expressions - in this case I'd use:
var qry = db.Treatment_Type
.Select(x => x.Project_Classification + ":" + x.Improvement_Type)
.AsEnumerable()
.ToDictionary<string, string>(x => x);
var qry = (from x in db.Treatment_Type
select new { TreatmentCode = x.Project_Classification + ":" + x.Improvement_Type }).AsEnumerable().ToDictionary<string, string>(x => x);
It's coming back as an anonymous type because you are using anonymous type annotation. which is. new {//some stuff}
Try
var qry = (from x in db.Treatment_Type
select x.Project_Classification + ":" + x.Improvement_Type ).ToDictionary<string, string>(x => x);
Try to change this ToDictionary<string, string>(x => x);
into this ToDictionary(x => x, x => x);
And i'm guessing that this two "Project_Classification" and "Improvement_Type" values are string Types.
精彩评论