我有一个对象模型MyObject,其中包含一个可空字节作为其属性之一。如何根据此键对MyObjects列表进行排序,以使列表按照该属性值升序排序,并在具有null的对象最后出现。
谢谢您的建议。
谢谢您的建议。
OrderBy
带有一个重载,可以接受IComparer
。这样,您就可以按照自己想要的方式对对象进行排序。public class NullByteComparer : IComparer<byte?>
{
public int Compare(byte? a, byte? b)
{
if (a == b)
return 0;
if (a == null)
return 1;
if (b == null)
return -1;
return return a < b ? -1 : 1;
}
}
yourObjects.OrderBy(x => x.NullByteProperty, new NullByteComparer());
IComparer<byte?>
接口的方法。??
运算符将 null
值强制排到后面,像这样:var res = myList.OrderBy(v => (uint?)v.NullableByteProp ?? uint.MaxValue);
uint?
,否则你的 null 值会与 0xFF 值一起排序。您可以使用GetValueOrDefault()函数,在null等于Byte.MaxValue时提供一个值。
var orderedValues = values.OrderBy(v => v.GetValueOrDefault(Byte.MaxValue));
null
放在第一位(小于所有其他值),因此您需要一个自定义的IComparer<T>
。 - James Michael Hare