【问题标题】:How to bypass or implement IComparable如何绕过或实现 IComparable
【发布时间】:2016-01-14 21:28:03
【问题描述】:

我收到以下错误,我不明白为什么以及如何克服它(或实施 icomparable)。

我正在尝试使用 Max() 从 Group 计数最多的对象中获取属性 Group。

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

}

至少一个对象必须实现 icomparable

【问题讨论】:

  • 你如何让List&lt;string&gt; 比另一个更大?

标签: c#


【解决方案1】:

我正在尝试从具有最长 list 的对象中获取属性 Group

你不想为此做Max。只需按列表的长度排序,然后取第一个:

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

【讨论】:

  • 谢谢.. 觉得我对所有 linqing 有点困惑 =)
猜你喜欢
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多