About sorting lists and delegates and lambda expressions Func stuff

List<bool> test = new List<bool>(); test.Sort(new Func<bool, bool, int>((b1, b2) => 1)); 

What am I missing?

Error 2 Argument 1: Cannot convert from "System.Func" to "System.Collections.Generic.IComparer"

Error 1 The best overloaded method match for "System.Collections.Generic.List.Sort (System.Collections.Generic.IComparer)" has some invalid arguments

When i have

 private int func(bool b1, bool b2) { return 1; } private void something() { List<bool> test = new List<bool>(); test.Sort(func); } 

It works great. Isn't that the same thing?

+6
source share
4 answers

Func is the wrong delegate type. You can use any of them:

 test.Sort((b1, b2) => 1); test.Sort(new Comparison<bool>((b1, b2) => 1)); 
+11
source

Because you need to pass System.Comparison<T> , not Func<something> . Omit new Func... and it should work.

 test.Sort((b1, b2) => !b1 && b2 ? -1 : b1 && !b2 ? +1 : 0); 
0
source

You can also try:

 test.Sort( delegate(bool b1,bool b2){return 1;}); 
0
source

Remove new Func<...>

 var test = new List<bool>(); test.Sort((a, b) => 1); 
0
source

Source: https://habr.com/ru/post/921154/


All Articles