我有一个 List
的 doubles
有几个值靠得很近,后面有一些相距很远;例如:
2.151, 2.152, 2.155, 100.1, 100.13, ...
我在想一些类似的事情:
if(abs(a[n] - a[n+1]) is within epsilon)
remove a[n+1] from a;
else continue;
获取类似的东西:
2.151, 100.1, ...
是否有我可以编写的 Linq(或某种 lambda 表达式)来执行此操作?
最佳答案
如果您不反对推出自己的扩展方法,您可以这样做:
public static IEnumerable<double> FuzzyDistinct(this IEnumerable<double> source, double epsilon)
{
// If source is null yield an empty enumerable.
if(source == null)
{
yield break;
}
// Get the source's enumerator.
var enumerator = source.GetEnumerator();
// If the source is empty yield an empty enumerator.
if(!enumerator.MoveNext())
{
yield break;
}
// Get the current item and yield it.
double current = enumerator.Current;
yield return current;
// Iterate over the remaining items, updating 'current' and yielding it
// if it does not fall within the epsilon of the previous value.
while(enumerator.MoveNext())
{
// Uncomment one of the following sections depending on
// your needs.
// Use this if the comparison is based on the previous
// item yielded.
//if(Math.Abs(enumerator.Current - current) > epsilon)
//{
// current = enumerator.Current;
// yield return current;
//}
// Use this if the comparison is based on the previous
// item, regardless of whether or not that item was yielded.
//if(Math.Abs(enumerator.Current - current) > epsilon)
//{
// yield return enumerator.Current;
//}
//current = enumerator.Current;
}
}
然后,例如,您可以这样调用它:
Enumerable
.Range(0, 10)
.Select(x => (double)x)
.FuzzyDistinct(1.5);
示例输出:
0 2 4 6 8
关于c# - 从列表中删除相似条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30338683/