33
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】自作クラスのListのソート

Last updated at Posted at 2018-03-27

自作クラスのListをSortさせる処理のメモ

public class Person
{
  // 名前
  public string Name { get; set; }
  // 年齢
  public int Age { get; set; }
}

public class Main
{
  List<Person> people = new List<Person>()
  {
    new Person(){ Name = "a", Age = 10 },
    new Person(){ Name = "b", Age = 11 },
    new Person(){ Name = "c", Age = 12 }
  };

  public Main()
  {
    // 年齢昇順
    people.Sort((a, b) => a.Age - b.Age);
    // 年齢降順
    people.Sort((a, b) => b.Age - a.Age);
    // 名前昇順
    people.Sort((a, b) => string.Compare(a.Name, b.Name));
  }
}

###まとめ
a - b で昇順
b - a で降順

33
38
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?