Reputation: 13308
var _maxID = from a in db.Articles
where a.CategoryId == categoryID
orderby a.Id descending
select new {ID = a.ID};
int maxID = _maxID.FirstOrDefault().Id;
This code gives me an error
Cannot implicitly convert type 'AnonymousType#1' to 'int'
How can I avoid this error?
Upvotes: 0
Views: 1127
Reputation: 21654
You could make it simpler and just use the Max function.
var _ids = from a in db.Articles
where a.CategoryId == categoryID
select a.ID;
int maxID = _ids.Max();
Upvotes: 3
Reputation: 1091
You can use(but you have to check for null before accessing)
int maxID = Convert.ToInt32(_maxID.FirstOrDefault().ID);
//or
int? maxID = _maxID.FirstOrDefault().ID as int;
//or
int maxID = (int)_maxID.FirstOrDefault().ID;
Upvotes: 1
Reputation: 9469
Don't use FirstOrDefault if you are not going to check for null before accessing the value. Just use First() then.
Second, you could select a.ID directly.
[...]
orderby a.Id descending
select a.ID
Upvotes: 1