【问题标题】:How to sort an array by value from an object如何按对象中的值对数组进行排序
【发布时间】:2020-11-15 10:52:05
【问题描述】:

如何按点赞数对数组进行排序? 我试过这样,但它不起作用。如果需要,我也可以使用列表而不是数组。

Array.Sort<Item>(items, (x, y) => x.Likes.Count.CompareTo(y.Likes.Count));

public class Item
{
    public long Id { get; set; }
    
    public string Text { get; set; }
    
    public Likes Likes { get; set; }

}
public class Likes
{
    public long Count { get; set; }

    public long UserLikes { get; set; }

    public long CanLike { get; set; }

    public bool CanPublish { get; set; }
}

【问题讨论】:

  • 看起来应该可以,您能否提供一组示例数据,以及您如何调用代码、输出是什么以及您期望的输出是什么?
  • 什么不起作用?实际结果和您的期望是什么?正如@LukeStorry 所写:这应该可行
  • 这似乎应该可以工作,但我建议使用 Linq 按功能排序:docs.microsoft.com/en-us/dotnet/api/…
  • 您也可以使用 LINQ:var sortedItems = items.OrderBy(i =&gt; i.Likes.Count).ToList()。如果您想首先拥有那些最喜欢的项目,请使用OrderByDescending
  • (x, y) =&gt; (x.Likes?.Count ?? -1).CompareTo(y.Likes?.Count ?? -1) 如果Likes 有可能是null

标签: c# arrays sorting


【解决方案1】:

如果Likes == null 有可能,那么构造不会工作:Likes.Count抛出异常;如果是你的情况,试试

(x, y) => (x.Likes?.Count ?? -1).CompareTo(y.Likes?.Count ?? -1)

比较:

Array.Sort<Item>(items, (x, y) => (x.Likes?.Count ?? -1).CompareTo(y.Likes?.Count ?? -1)); 

这里我们假设Likes == null 表示Likes.Count == -1,所以这些Likes == null 案例将在顶部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2021-08-10
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多