C # - sorting a list - x and y
I have this code and I understand that it is sorting the list lstDMV
. But please help me break it down.
lstDMV.Sort((x, y) => DateTime.Compare(x.NotifDate, y.NotifDate));
What does it mean =>
? And how does this work based on the integer returned by the comparison function?
How can I sort mine lstDMV
if I am sorting integers instead of dates?
source to share
He named the expression lambda . For a comparison itself, take a look at the DateTime.Compare method . Check out its return values:
- <0 β t1 before t2
- 0 β t1 coincides with t2
- > 0 β t1 later t2
source to share
It's called lambda operator
. From MSDN;
The => icon is called the lambda operator. It is used in lambda expressions to separate input variables on the left side of the lambda body on the right side . Lambda expressions are inline expressions similar to anonymous methods, but more flexible; they are widely used in LINQ queries that are expressed in method syntax.
For the sorting operation, use a method Sort()
like:
lstDMV.Sort((int1, int2) => int1.CompareTo(int2));
source to share
=> is the lambda expression operator, which you can think of as an anonymous function in javascript
in this case
lstDMV.Sort ((x, y) => DateTime.Compare (x.NotifDate, y.NotifDate)); it creates a function that is used as a handler for the sort event. The compiler can infer the types x and y since it knows that the problem is closing the Delelegate.
source to share
First of all, these are lambda expressions. Now to your question: => is an operator that defines the return value.
In your case (x,y)
will return a value DateTime.Compare(x.NotifDate, y.NotifDate)
. Now Sort()
- your list function is somehow sorting the list based on the value DateTime.Compare(x.NotifDate, y.NotifDate)
.
Take a look at the MSDN article: http://msdn.microsoft.com/en-us/library/bb397687.aspx This is very helpful.
source to share
(Others have already answered lambda operator
part of your question)
how can i sort my lstDMV if i am sorting integers instead of dates?
ints.Sort((i1, i2) => i1.CompareTo(i2));
source to share