c# - 从列表中删除相似条目

标签 c# linq

我有一个 Listdoubles 有几个值靠得很近,后面有一些相距很远;例如:

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/

相关文章:

c# - 使用类从 asp.net 中的数据库填充下拉列表的方法是什么?

C# Linq Where(表达式).FirstorDefault() 与 .FirstOrDefault(表达式)

c# - 什么时候使用内存映射文件?

c# - Linq:如何按多对多关系分组?

.net - LINQ to Entities 无法识别该方法

c# - CreateDocumentQuery 与 LINQ 一起使用时会引发异常,与 SQL 一起使用时则正常

c# - 选择投影中的索引

c# - 快速读取大量文件

C#,在设计基本颜色类时正确使用 static 关键字

c# - Curl 中的 400 错误请求