The problem is with your Compare function. You should state some ordering, like false < true or true < false. In your function, sometimes true < false and sometimes false < true.
Sorting custom list with bool
문제
There is a class
public class Camera
{
...
public bool live;
...
}
This is the sorting class
public class CameraSortByLive : IComparer<Camera>
{
private bool asc;
public CameraSortByLive(bool a)
{
this.asc = a;
}
public int Compare(Camera x, Camera y)
{
if (x.live != y.live)
return asc ? 0 : 1;
else
return asc ? 1 : 0;
}
}
This is how I use it:
List<Camera> CameraList = new List<Camera>();
CameraList.Sort(new CameraSortByLive(sortAsc));
Now, I beside live
member I have other members int
, string
type. With those types I have similar sorting class implementing IComparer
. There is no problem with them. The only problem with this live
member. It simply doesn't sort. I expect it to go either on top of list or bottom, but it goes somewhere in the middle. What am I missing?
해결책
다른 팁
public int Compare(Camera x, Camera y)
{
return (asc && x.live) ? 1 : 0;
}
The problem with your code is that you can't be really sure the order in which the list elements are compared to each other. So, you are comparing two cams and if their live
member is equal you consider the first is "greater" than second. So, if your first cam have is "dead" and second is "live", the first is still greater. That definitely not what you want.
With this code, if the left cam is live - it's considered greater than right, regardless of right's live value. Since we're not concerned about sorting by other features, we really don't care of "internal" order of live cams (i.e. all live cams are considered equal, as well as all deadcams considered equal too)