【问题标题】:Sort an array of objects by value in C#? [duplicate]在 C# 中按值对对象数组进行排序? [复制]
【发布时间】:2017-03-04 03:49:23
【问题描述】:

我有一个对象数组,每个对象都包含一个用户 ID 和金额。我将如何对这个数组进行排序,以使金额最大的对象成为数组中的第一个元素,最后一个是钱最少的人?

【问题讨论】:

标签: c#


【解决方案1】:

我会用 LINQ orderBy 来做这件事

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void OrderByEx1()
{
    Pet[] pets = { new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };

    IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);

    foreach (Pet pet in query)
    {
        Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
    }
  }

【讨论】:

    【解决方案2】:

    升序排列:

     var newList = YourObj.OrderBy(x => x.Price).ToList();
    

    降序排列:

      var newList = YourObj.OrderByDescending(x => x.Price).ToList();
    

    【讨论】:

    • 如果你想回答有大量重复的问题,至少提供一个答案。 List&lt;T&gt; 不是数组。
    猜你喜欢
    • 2013-02-24
    • 2021-12-03
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多