有没有一种方法可以用LINQ优化前臂

本文关键字:LINQ 优化 方法 一种 有没有 | 更新日期: 2023-09-27 17:57:49

如何检查整数数组是否包含整数值。

我怎么能在LiNQ做到这一点。我必须在LINQ查询中完成。。

类似:-

   Int test = 10;
var a = from test in Test
        where test.Contains(1,2,3,4,5,6,7,8,9,10)
    select test.id

目前我是通过扩展方法来完成的,但是这个方法很慢。

public static bool ContainsAnyInt(this int int_, bool checkForNotContain_, params int[] values_)
    {
    try
            {
                if (values_.Length > 0)
                {
                    foreach (int value in values_)
                    {
                        if (value == int_)
                        {
                            if (checkForNotContain_)
                                return false;
                            else
                                return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Log("Exception:  ExtensionsMerhod - ContainsAnyInt() Method ---> " + ex);
            }
}

我必须以优化的方式来做,因为数据是巨大的。。。

有没有一种方法可以用LINQ优化前臂

在大多数情况下,Linq比foreach慢。

您可以直接调用LinqExtension方法:

int[] values = new[]{3,3};
bool hasValue = values.Contains(3);

它完成了与您的扩展方法相同的事情。

以下不会更快地工作吗(未经测试):

public static bool ContainsAnyInt(this int int_, bool checkForNotContain_, params int[] values_)
{
    if(values_ != null && values_.Contains(int_))
    {
       return !checkForNotContain_;
    }
    else
       return false;
}

在您的约束下工作,我会对每个测试类中的值数组进行排序,这样您就可以执行以下操作:

int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var results = from test in tests
              where test.BinaryContains(values)
              select test.id;

测试类看起来像:

class Test
{
    public int id;
    public int[] vals; //A SORTED list of integers
    public bool BinaryContains(int[] values)
    {
        for (int i = 0; i < values.Length; i++)
            if (values[i] >= vals[0] && values[i] <= vals[vals.Length])
            {
                //Binary search vals for values[i]
                //if match found return true
            }
        return false;
    }
}

当然,有很多方法可以进一步优化它。如果内存不是问题,Dictionary可以为您提供包含给定整数的所有测试类。