转换通用集合排序以利用 Linq

发布于 2024-08-17 16:24:33 字数 737 浏览 4 评论 0原文

我有一段现有的代码用于对对象列表进行排序。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二手情话 2024-08-24 16:24:33

不完全是,但也很接近了。第一个可以

List<Product> productsList = new List<Product>() {
    new Product { StartDatetime = new DateTime(2010, 1, 1), SomeId = 2 },
    new Product { StartDatetime = new DateTime(2010, 1, 1), SomeId = 4 }
};

按相反的顺序排序(首先 SomeId 等于 4,第二个 SomeId 等于 2),但第二个将把它们排序为 ProductSomeId 等于 2 第一个和 ProductSomeId 等于 4 秒。这是因为当前定义的委托不处理两个 SomeId 不为 null 且不同的任何情况。因此,就委托而言,上述两个 Product 是“相等的”,但根据 LINQ 查询,它们并不相等。

Not quite but it's close. The first could order

List<Product> productsList = new List<Product>() {
    new Product { StartDatetime = new DateTime(2010, 1, 1), SomeId = 2 },
    new Product { StartDatetime = new DateTime(2010, 1, 1), SomeId = 4 }
};

in the opposite order (with SomeId equals 4 first and SomeId equals 2 second) but the second will order them as the Product with SomeId equals 2 first and the Product with SomeId equals 4 second. This is because the delegate, as it is currently defined, does not handle any case where two SomeIds are non-null and different. So, as far as the delegate concerned, the above two Products are "equal" but according to the LINQ query they are not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文