I have a issue I havn’t yet been able to find a solution on. To simplify the issue: I have two SQL tables and I’m using LinQ to SQL. The two tables represents Courses, where CourseType contains CourseName and TotalSpots, and CourseInstance contains CourseDate, AmountSignedUp and a refrence to CourseType. There’s a one to many relation between CourseType and CourseInstance.
Now what I need help with is the Linq query/Lambda expression to sort both CourseType and CourseInstance (if it’s posible). I want the CourseType to be sorted after how many in total free spots (calculated from every CourseInstance under CourseType; CourseType.TotalSpots – CourseInstance.SignedUp), where the CourseType with most free spots shows first. I want CourseInstance to be sorted simlar, by how many free spots that CourseInstance has (CourseType.TotalSpots – CourseInstance.AmountSignedUp).
I can’t get my head around how to solve this. I’ve looked at simlar questions and issue and this is what I’ve made so far, just to give a basic idea:
Edit: I’ve done this code so far which will sort the CourseType correctly. I’m not sure how I can get the CourseInstance sublist sorted (CourseType.CourseInstance). I guess I’ll have to do it later in the code when I’m converting it to a list unless someone has a good solution for this. I could do it as Arion suggested, why I’ll mark his answer.
var result= (
from c in _db.CourseType
orderby ((c.TotalSpots * c.CourseInstance.Count) - c.CourseInstance.Sum(
ci => (ci.AmountSignUp ?? 0))) descending
select c
);
I am not really sure what you want. But kinda sounds like you want to order by the
c.TotalSpots - ci.AmountSignedUp. So is not this enough?where db is the linq data context.
Or if
c.TotalSpotsandci.AmountSignedUpisnullablethen like this:I am still not sure want you want but. You could do this: