List< double>的GroupBy宽容行不通 [英] GroupBy of List<double> with tolerance doesn't work

查看:67
本文介绍了List< double>的GroupBy宽容行不通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#的Groupby有疑问.

我制作了一个List,如下所示:

I made a List like shown below:

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);  

我想按以下方式对这些号码列表进行分组:

I'd like to group these number list like this:

group 1 => 1  
group 2 => 2.1 , 2.0  
group 3 => 3.0 , 3.1 , 3.2  
group 4 => 4.2

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

so, I wrote code like this:

var testListGroup = testList.GroupBy(ele => ele, new DoubleEqualityComparer(0.5));

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);
    }

    public int GetHashCode(double d)
    {
        return d.GetHashCode();
    }
    public bool EQ(double dbl, double compareDbl, double tolerance)
    {
        return Math.Abs(dbl - compareDbl) < tolerance;
    }
}

但是GroupBy子句不能像下面这样工作:

Yet the GroupBy clause doesn't work like the this:

group 1 => 1  
group 2 => 2.1
group 3 => 2.0  
group 4 => 3.0
group 5 => 3.1
group 6 => 3.2
group 7 => 4.2

我不知道问题是什么.请让我知道是否有问题和解决方案.

I don't know what the problem is. Please let me know if there is problem, and solutions.

推荐答案

使用简单的

use simple Math.Floor to get lower range of the number so that 5.8 should not be treated as 6.

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);
testList.Add(5.8);
testList.Add(5.5);

var testListGroup = testList.GroupBy(s => Math.Floor(s)).ToList();

这篇关于List&lt; double&gt;的GroupBy宽容行不通的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆