- 1. 概要
- 2. 使い方
1. 概要
説明だけ読むと「数の符号を示す整数を返します」と書いてありまして、これだけでは、よく分からない。
2. 使い方
List<double> list = new List<double>{ 0.5, 0.3, 0.8, 0.2 };
てな、「List」がありまして、これをソートしたいからちゅうて。
list.Sort((x, y) => x - y);
と書きますと。
error CS1662: Cannot convert `lambda expression' to delegate type `System.Comparison<double>' because some of the return types in the block are not implicitly convertible to the delegate return type
てなエラーになります。
ソートするための戻りは、正数でなきゃならないのでね。
これを解決するのに「Math.Sign」を使用します。
using System;
using System.IO;
using System.Collections.Generic;
public class MyMain
{
static public void Main ()
{
List<double> list = new List<double>{ 0.5, 0.3, 0.8, 0.2 };
list.Sort((x, y) => Math.Sign(x - y));
foreach (double item in list)
{
Console.WriteLine("item = [" + item + "]");
}
}
}
上記のソースをコンパイルして、実行すると、下記の結果が得られます。
item = [0.2]
item = [0.3]
item = [0.5]
item = [0.8]
|
|