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?

+3


source to share


6 answers


Lambda operator =>

in

lstDMV.Sort((x, y) => DateTime.Compare(x.NotifDate, y.NotifDate));

      

basically creates a new delegate with a code block for excecute. X and y are passed as parameters.



you can sort the int list by changing the code to

lstDMV.Sort((x, y) => x.CompareTo(y));

      

+2


source


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
+2


source


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));

      

+2


source


=> 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.

+1


source


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.

+1


source


(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));

      

+1


source







All Articles