Converting to an int in LINQ not working?
The following query complains that the int conversion is not supported.
var list = from d in data
where d.Id == (int)GridView1.DataKeys[0].Value
select d;
It complains on the (int)GridView1.SelectedInex line telling me that the Int conversion is not supported. I also tried Convert.ToInt32, but that did not work either.
Is this logic that has to be calculated before such as above the linq query or is there a special way to do it and if not, why does it 开发者_StackOverflow中文版not support it?
Why not try and parse the value to an integer before hand, it's not needed in the query.
Int id;
if (Int32.TryParse(ridView1.DataKeys[0].Value.ToString(), out id))
{
var list = from d in data
where d.Id == id
select d;
}
I assume the semicolon after the where line is a typo?
Pull the cast outside the linq query, it's trying to generate SQL for the cast operation, which isn't supported
int id = (int)GridView1.DataKeys[0].Value;
var list = from d in data
where d.Id = id
select d;
you are casting, not converting.
int.Parse( GridView1.DataKeys[0].Value )
would be converting.
GridView1.DataKeys[0].Value returns an object which may or may not be an int.
I'm guessing here, but try:
where d.Id == (int)(GridView1.DataKeys[0].Value);
in case it's trying to cast the GridView.
(edit: fixed code - see comment on question)
This answer is wrong!
精彩评论