GroupBy
使用自定义比较器进行聚类的另一个想法
var numbers = new float[]
{
3.4f, 5.0f, 6.1f, 144.0f, 144.14f, 145.0f,
147.0f, 273.77f, 275.19f, 279.0f, 399.4f, 399.91f, 401.45f,
49, 50, 51,
533.26f, 537.0f, 538.9f
};
foreach (var group in numbers.GroupBy(i => i, new ClosenessComparer(4f)))
Console.WriteLine(string.Join(", ", group));
和习俗ClosenessComparer
:
public class ClosenessComparer : IEqualityComparer<float>
{
private readonly float delta;
public ClosenessComparer(float delta)
{
this.delta = delta;
}
public bool Equals(float x, float y)
{
return Math.Abs((x + y)/ 2f - y) < delta;
}
public int GetHashCode(float obj)
{
return 0;
}
}
和输出:
1: 3,4 5 6,1
2: 144 144,14 145 147
3: 273,77 275,19 279
4: 399,4 399,91 401,45
6: 49 50 51
5: 533,26 537 538,9