dciliske
dciliske

Reputation: 157

Linq results to IEnumerable invalid cast

Question for Linq users out there: I'm getting an InvalidCastexception: Specified cast is not valid whenever I try to obtain an IEnumerable from revs after making the Linq query. There database is populated and it should be returning values.

Specifically, the error is occurring on the line List<PDP> rev = revs.ToList<PDP>();

Any ideas what's going on?

short ret;
using (DataContext db = new DataContext())
{
    var play = from p in db.PDP
        where p.ID == id
        select p;
    var revs = play.OrderByDescending(p => p.revision);
    List<PDP> rev = revs.ToList();
    var revNum = revs.ToList().Count() > 0 ? rev.First().revision : 0;
    ret = (short)revNum;
}

EDIT
I've clarified some parts of the code.

EDIT 2
rev exists as a debugging variable to narrow down where the error was.

The original code was:

short ret;
using (GasForecastDataContext db = new GasForecastDataContext())
{
    var play = from p in db.PDP
        where p.Play_ID == play_id
        select p;
    var revs = play.OrderByDescending(p => p.revision);
    var revNum = revs.Count > 0 ? rev.First().revision : 0;
    ret = (short)revNum;
}

Upvotes: 3

Views: 1565

Answers (4)

recursive
recursive

Reputation: 86064

It seems like the elements in db.PDP are some type other than PDP, or if it is PDP, it may be in another namespace.

Upvotes: 1

Brandon Moretz
Brandon Moretz

Reputation: 7621

Is there a specific reason you're declaring the "rev" list variable at all? "Count()" and "First()" are available on IEnumerable interface ( "revs" ).

short ret;

using (DataContext db = new DataContext())
{
    var play = from p in db.PDP
        where p.ID == id
        select p;

    var revs = play.OrderByDescending(p => p.revision);

    ret = (short) revs.Count() > 0 ? revs.First().revision : 0;
}

Upvotes: 1

Andrew
Andrew

Reputation: 14447

Try this:

List<PDP> rev = revs.ToList<PDP>();

I just added the type for the generic.

Upvotes: 0

Narnian
Narnian

Reputation: 3908

Wouldn't it still be an IQueryable?

rev could probably be cast as an IEnumberable, but revs is probably still IQueryable.

You might be able to call ToList() on revs.

Upvotes: 0

Related Questions