Reputation: 5566
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});
Upvotes: 0
Views: 198
Reputation: 510
You can also use
select new {b.startMiles, b.endMiles}).FirstOrDefault();
on your linq statement
Upvotes: 1
Reputation: 34238
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;
}
Upvotes: 2
Reputation: 160852
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);
Upvotes: 3
Reputation: 3909
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.
Upvotes: 2