4

I get the below error and I can't understand why and how to get past it (or implement icomparable).

I'm trying to get the property Group from the object that has the biggest count of Group 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

MrProgram
  • 5,044
  • 13
  • 58
  • 98

1 Answers1

6

I'm trying to get the property Group from the object that has the longest list

You don't want to do Max for that. Simply 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;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523