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