Question about linq query format
var q = (dc.tblHel开发者_如何学GopCentreQuestions.Where(c => c.userID == UserID));
q.OrderByDescending(c => c.dateSubmitted);
I'm just getting used to Linq, and I'm sorting my records by date submitted descending, but could someone explain to me why I have to do c => c.dateSubmitted
and not just pass in tblHelpCentreQuestions.dateSubmitted
? What does the c=>
do and why is it needed?
It is a lambda expression. Read about them here.
Also note that OrderByDescending returns a new IEnumerable, it does not do an in-place sort. You will want to read about Linq basics here.
q = tblHelpCentreQuestions is enumerable. It does not have dateSubmitted property. Its elements have that property. C stands exactly for that element
the c=>c.dateSubmitted
is a lambda expression, they are used a lot with Linq. In this case, it's kind of a selector. it defines which property of your class to order by. tblHelpCentreQuestions.dateSubmitted
in the other hand is just a "value", it doesn't give info about the property.
Put simply, a lambda expression is an anonymous method. a method needs parameters, that's what the c=>
is for. if you have a method that takes two arguments (say, sender and args), you would have something like (sender, args)=>
. There are Expression Lambdas, which have one expression as their body (as is the case with your example), and Statement Lambdas which can have more than one instruction (or statement), and thus need a block to delimit it. (sender, args)=>{ ... }
. It may or may not have a return value.
Hope this helps :)
精彩评论