c# - 在 C# 中将多个参数传递给 Func<>

标签 c# linq

这是来自编程测试,所以我确信有更好的方法来做到这一点,但问题需要这个特定的答案。

我有一个 Result 方法,它简单地匹配一个谓词并返回一个 bool 值,并且有问题的谓词检查一个字符串数组以报告是否有任何字符串超过长度 5。

static bool Result<T>(T[] values, Func<T, bool> predicate)
{
    if (values.Where<T>(predicate).Count() > 0)
        return true;
    else
        return false;
}

static bool StringLengthLessThan5(string str)
{
    return str.Length < 5;
}

最后这个是这样用的——

bool val2 = Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, StringLengthLessThan5);

这按预期工作,但是现在我需要使用相同类型的代码但参数化 Func 以允许字符串长度的动态值,即我的 Func<string,bool>现在需要 Func<string,int,bool>

static bool StringLengthLessThanGivenNumber(string str,int length)
{
    return str.Length < length;
}

或者,

static Func<string, int, bool> FuncForDynamicStringlength = (s, i) => s.Length < i;

我的问题是,本着保持新 Func 的调用代码不变的精神,即我仍然想使用 -

Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, StringLengthLessThanGivenNumber);

但是,我该如何传递参数呢?

Func 现在需要 2 个参数,第一个是字符串,第二个是 int,我如何传递第一个参数?我可以传递 int 长度进行比较,但我对第一个参数感到困惑。

我意识到我可以遍历我的 string[] 并像这样在 foreach 中调用 Func(我知道这在这个特定实例中没有意义,因为我正在覆盖 bool 的值,但我确定你明白我的问题)-

foreach(string str in new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" })
{
    bool val3_1 = StringLengthLessThanGivenNumber(str, 5);
}

但如果可能的话,我想使用我的原始代码。

最佳答案

只需将谓词包装到 lambda 表达式中,然后使用变量或常量传递所需的长度,如下所示:

int len = 5;
bool val1 = Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, x => StringLengthLessThanGivenNumber(x, len));
bool val2 = Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, x => StringLengthLessThanGivenNumber(x, 5));

解决这个问题的另一种方法是为 string 集合定义扩展方法。

public static class StringCollectionExtensions
{
    public static bool HasLengthLessThan(this IEnumerable<string> collection, int length)
    {
        return collection.Any(x => x.Length < length);
    }
}

然后你可以像这样使用它:

var testStrings = new string[5] {"asdf", "a", "asdsffsfs", "wewretete", "adcv"};

bool val3 = testStrings.HasLengthLessThan(6);

关于c# - 在 C# 中将多个参数传递给 Func<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524193/

相关文章:

c# - 使用 Entity Framework 6 调用数据库函数

c# - 创建 pdf 错误消息(...文件已损坏且无法修复)

c# - 为什么 C# 编译器在将方法组作为参数传递时不解析仅返回类型不同的委托(delegate)类型?

c# - 将样式应用于放置在 C# 代码中的 <a href> 标记

c# - 配置 Asp.net MVC 项目和 EntityFramework 以使用 Redis 作为缓存提供程序

c# - LINQ:在子实体内部搜索

c# - 在C#项目中使用C++ DLL

c# - 如何将 Linq 扩展方法与 CodeFluent 实体模板一起使用?

c# - 组合表达式(表达式<Func<TIn,TOut>> 与表达式<Func<TOut, bool>>)

c# - 选择文本文件用作 Unity 中的字典