How to get around or implement IComparable

I get the following error, and I can’t understand why and how to overcome it (or implement icomparable).

I am trying to get the Group property from an object that has the most groups using Max ().

 public class Program
{
    private static void Main(string[] args) {
        var list = new List<Foo>();

        for (var i = 0; i < 10; i++) {
            list.Add(new Foo());
            if (i == 5) {
                var foo = new Foo() {
                    Group = { "One", "Two", "Three" }
                };
                list.Add(foo);
            }
        }

        var maxGroup = list.Max(x => x.Group); //throws error
    }

}

public class Foo {
    public Guid Id { get; } = new Guid();
    public int Field1 { get; set; }
    public int Field2 { get; set; }
    public int Field3 { get; set; }
    public int Field4 { get; set; }

    public List<string> Group { get; set; } = new List<string>();

}

at least one object must implement icomparable

+4
source share
1 answer

I am trying to get a property Groupfrom the object with the longestlist

You do not want to do Maxthis. Just order by the length of the list and take the first one:

Foo res = list.OrderByDescending(x => x.Group.Count).FirstOrDefault();
if (res != null) {
    List<string> longestList = res.Group;
}
+6
source

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


All Articles