测试单个对象是否与 Func<T, bool> 匹配

Hel*_*mut 2 c#

我有一个对象(数据库中的一条记录),想要检查该对象是否与Func<T, bool>.

我通过将对象添加到对象列表中解决了这个问题,并尝试使用 where 子句从该列表中获取它,给定这样的条件

var testMatch = new Test
{
    t1 = "123"
};

// Query is stored in a string and compiled with Sprint.Filter.OData to p => p.t1 == "123"
var query = "t1 eq '123'";
var compiledQuery = Filter.Deserialize<Test>(query).Compile();

// This works like expected
Console.WriteLine(Match<Test>(compiledQuery, testMatch));

public bool Match<T>(Func<T, bool> condition, T testObject)
{
    var test = new List<T>();
    test.Add(testObject);
    var t = test.Where(condition).FirstOrDefault();
    return (t != null);
}

public class Test
{
    public string t1 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

因此,这按预期工作,但我想知道是否有比创建列表、将其添加到此列表并尝试使用条件检索它更简单的方法来测试单个对象。

我错过了一些非常简单的事情吗?

Swe*_*per 6

Func<T, bool>字面意思是一个接受 aT并返回 a 的函数boolT在本例中,它是一个返回 a是否满足条件的函数,这正是您想要的

你可以直接调用它:

bool satisfiesCondition = compiledQuery(testMatch);
Run Code Online (Sandbox Code Playgroud)

你不需要把它给Where. 您认为如何Where实施?WhereFunc<T, bool>像这样调用您提供的,以确定该对象是否应该在IEnumerable<T>它返回的中。