小编kdm*_*kdm的帖子

列表<double>的GroupBy具有容差不起作用

Groupby对C#有疑问.

我做了List如下所示:

List<double> testList = new List<double>();

testList.Add(1);    
testList.Add(2.1);  
testList.Add(2.0);  
testList.Add(3.0);  
testList.Add(3.1);  
testList.Add(3.2);  
testList.Add(4.2);  
Run Code Online (Sandbox Code Playgroud)

我想将这些数字列表分组如下:

group 1 => 1  
group 2 => 2.1 , 2.0  
group 3 => 3.0 , 3.1 , 3.2  
group 4 => 4.2
Run Code Online (Sandbox Code Playgroud)

所以,我写了这样的代码:

var testListGroup = testList.GroupBy(ele => ele, new DoubleEqualityComparer(0.5));
Run Code Online (Sandbox Code Playgroud)

DoubleEqualityComparer 定义是这样的:

public class DoubleEqualityComparer : IEqualityComparer<double>
{
    private double tol = 0;

    public DoubleEqualityComparer(double Tol)
    {
        tol = Tol;
    }

    public bool Equals(double d1,double d2)
    {
        return EQ(d1,d2, tol); …
Run Code Online (Sandbox Code Playgroud)

c# linq

5
推荐指数
1
解决办法
652
查看次数

标签 统计

c# ×1

linq ×1