0

I am struggling to select multiple columns in the carCheckouts table. I just want the startMiles and endMiles from one row that I know the pk of. Is my linq statement correct? if so how do I turn b.startMiles and b.endMiles into usable variables after? Thanks

var m = (from b in db.carCheckouts
where b.pk == primaryKey
select new {b.startMiles, b.endMiles});

4 Answers 4

3

Your current query returns an IQueryable of an anonymous type - but it sounds like you want a single item:

var m = (from b in db.carCheckouts
where b.pk == primaryKey
select new {b.startMiles, b.endMiles}).Single();

Now you can use the properties of m just so:

Console.WriteLine("Start Miles:"  + m.startMiles);
Sign up to request clarification or add additional context in comments.

1 Comment

Understand that the Single() call will only return without error if there is EXACTLY one result of the query. This should be valid for a search on a PK you know exists, but in other circumstances there may be no such record matching the filter, or many. SingleOrDefault will return without exception if there are 0 or 1 items; FirstOrDefault will work in cases of zero to many results.
2

You've turned m into an anonymous type (actually m will be an IQueryable<> of that anon type) that can be used anywhere inside the scope it's declared. Anon types were added to allow something like this so you don't have pre-create a type that would hold these values, you create the type on the fly.

If you want to only have 1 and not an IQueryable you can do .FirstOrDefault or just .First to give you the 1 instance of that anon type.

Comments

2
var m = (from b in db.carCheckouts
where b.pk == primaryKey
select new {b.startMiles, b.endMiles});

double totalMiles;

foreach(var item in m)
{
    totalMiles = item.endMiles - item.startMiles;
}

Comments

1

You can also use

select new {b.startMiles, b.endMiles}).FirstOrDefault();

on your linq statement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.