At least one object must implement IComparable

后端 未结 5 365
攒了一身酷
攒了一身酷 2020-12-06 08:48
using System;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
             


        
相关标签:
5条回答
  • 2020-12-06 09:25

    You Player class needs to implement the IComparable interface..

    http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx

    0 讨论(0)
  • 2020-12-06 09:36

    Your Player class must implement the IComparable interface. The SortedSet holds the items in a sorted order, but how would it know what the sorted order is if you haven't told it how to sort them (using IComparable)?

    0 讨论(0)
  • 2020-12-06 09:38

    Well, you're trying to use SortedSet<>... which means you care about the ordering. But by the sounds of it your Player type doesn't implement IComparable<Player>. So what sort order would you expect to see?

    Basically, you need to tell your Player code how to compare one player with another. Alternatively, you could implement IComparer<Player> somewhere else, and pass that comparison into the constructor of SortedSet<> to indicate what order you want the players in. For example, you could have:

    public class PlayerNameComparer : IComparer<Player>
    {
        public int Compare(Player x, Player y)
        {
            // TODO: Handle x or y being null, or them not having names
            return x.Name.CompareTo(y.Name);
        }
    }
    

    Then:

    // Note name change to follow conventions, and also to remove the
    // implication that it's a list when it's actually a set...
    SortedSet<Player> players = new SortedSet<Player>(new PlayerNameComparer());
    
    0 讨论(0)
  • 2020-12-06 09:43

    Make your Player class implement IComparable.

    0 讨论(0)
  • 2020-12-06 09:47

    This is a more general answer to this error i suppose.

    This line will fail with the error you got:

    Items.OrderByDescending(t => t.PointXYZ);
    

    However you can specify how to compare it directly:

    Items.OrderByDescending(t => t.PointXYZ.DistanceTo(SomeOtherPoint))
    

    Then you dont need the IComparable interface. Depends on the API you are using. In my case i have a Point and a DistanceTo-method. (Revit API) But an integer should be even easier to determine the "size/position" of.

    0 讨论(0)
提交回复
热议问题