C#でリストをソートする方法

C#でリストをソートしたい場合はLINQのOrderByを使うと簡単にできるようです。

using System;
using System.Collections.Generic;
using System.Linq;

public class Example1
{
  static public void Main ()
  {
    List list = new List<:int> { 321, 432, 123 };
    list = list.OrderBy(i => i).ToList();
    foreach(int i in list) {
      Console.WriteLine(i);
    }
  }
}

実行結果

123
321
432

構造体の場合も同じような感じでできます。

using System;
using System.Collections.Generic;
using System.Linq;

public class Example2
{
  struct Example
  {
    public string name;
    public int value;
  }

  static public void Main ()
  {
    List list = new List<Example> {
      new Example { name = "aaa", value = 321 },
      new Example { name = "bbb", value = 432 },
      new Example { name = "ccc", value = 123 }
    };

    list = list.OrderBy(e => e.value).ToList();
    foreach(Example e in list) {
      Console.WriteLine("{0}: {1}", e.name, e.value);
    }
  }
}

実行結果

ccc: 123
aaa: 321
bbb: 432

リンク

Enumerable.OrderBy Method (System.Linq) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=netframework-4.7.2

幾何学関係アルゴリズムで参考になりそうなリポジトリー

2Dの幾何学関係のアルゴリズムで参考になりそうなリポジトリー

2つの円の共有点

Algorithms/CircleCircleIntersectionPoints.js at master · williamfiset/Algorithms · GitHub
https://github.com/williamfiset/Algorithms/blob/master/com/williamfiset/algorithms/geometry/CircleCircleIntersectionPoints.js

円と直線の共有点

Algorithms/LineCircleIntersection.js at master · williamfiset/Algorithms · GitHub
https://github.com/williamfiset/Algorithms/blob/master/com/williamfiset/algorithms/geometry/LineCircleIntersection.js

2つの直線の共有点

Algorithms/Line.java at master · williamfiset/Algorithms · GitHub
https://github.com/williamfiset/Algorithms/blob/master/com/williamfiset/algorithms/geometry/Line.java

他にも線形代数やグラフ理論など数学系のコードがあるようです。

リンク

GitHub – williamfiset/Algorithms: A collection of algorithms
https://github.com/williamfiset/Algorithms

Enumerable.Range

以前、LinqのSelectを使ってPythonのmapのような操作をする方法を書きました。

そこでは、

int[] a = new int[]{ 0, 1, 2, 3, 4 };

としていましたが、new int[]の代わりにEnumerable.Rangeを使うという方法もあるそうです。

using System;
using System.Linq;
using System.Collections.Generic;

public class Example
{
  static public void Main ()
  {
    IEnumerable<int> a = Enumerable.Range(0, 5).Select(x => x * 2 + 1);
    foreach(int v in a) {
      Console.WriteLine(v);
    }
  }
}

実行結果

1
3
5
7
9

リンク

Enumerable.Range Method (Int32, Int32) (System.Linq)
https://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.110).aspx