转换通用集合排序以利用 Linq
我有一段现有的代码用于对对象列表进行排序。
productsList.Sort(
delegate(Product p1, Product p2)
{
int result = p1.StartDatetime.CompareTo(p2.StartDatetime);
if (result == 0)
{
if (p1.SomeId == p2.SomeId)
{
result = 0;
}
else if (p1.SomeId == null)
{
result = -1;
}
else if (p2.SomeId == null)
{
result = 1;
}
}
return result;
});
我有一种感觉,可以通过将其替换为来简化:
productsList = productsList
.OrderBy(p => p.StartDatetime)
.ThenBy(p => p.SomeId)
.ToList();
我的假设正确吗?
I have an existing bit of code for sorting a list of objects.
productsList.Sort(
delegate(Product p1, Product p2)
{
int result = p1.StartDatetime.CompareTo(p2.StartDatetime);
if (result == 0)
{
if (p1.SomeId == p2.SomeId)
{
result = 0;
}
else if (p1.SomeId == null)
{
result = -1;
}
else if (p2.SomeId == null)
{
result = 1;
}
}
return result;
});
I have a feeling that this can be simplified by replacing it with:
productsList = productsList
.OrderBy(p => p.StartDatetime)
.ThenBy(p => p.SomeId)
.ToList();
Am I correct in my assumption?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不完全是,但也很接近了。第一个可以
按相反的顺序排序(首先
SomeId
等于4
,第二个SomeId
等于2
),但第二个将把它们排序为Product
与SomeId
等于2
第一个和Product
与SomeId 等于
4
秒。这是因为当前定义的委托不处理两个SomeId
不为 null 且不同的任何情况。因此,就委托而言,上述两个Product
是“相等的”,但根据 LINQ 查询,它们并不相等。Not quite but it's close. The first could order
in the opposite order (with
SomeId
equals4
first andSomeId
equals2
second) but the second will order them as theProduct
withSomeId
equals2
first and theProduct
withSomeId
equals4
second. This is because the delegate, as it is currently defined, does not handle any case where twoSomeId
s are non-null and different. So, as far as the delegate concerned, the above twoProduct
s are "equal" but according to the LINQ query they are not.