我想搜索所有为空或不为空的记录。我可以这样做(示例代码):
public ICollection<Employees> SearchForPhoneNumberNull()
{
return collection.Where(x => x.PhoneNumber == null);
}
public ICollection<Employees> SearchForPhoneNumberNotNull()
{
return collection.Where(x => x.PhoneNumber != null);
}
Can i somehow connect these two methods, and for example send some variable that will decide is it !=
or ==
?
当然,像这样:
对于处理空电话号码和非空电话号码的单个功能,我将实现扩展功能。
这里有一些重要的事情要注意。
Extension functions must be in a static class (i.e.,
static class EmployeesExtensions
this ICollection<Employees> collection
this
enables the function to be used as an extension function.Func<Employees, bool> predicate
bool
(i.e., True/False).e => e.PhoneNumber == null
.Where()
by name,predicate
.ToList()
is needed to convert theIEnumerable<Employees>
toICollection<Employees>
. However, this forces the evaluation of the LINQ expression tree that you are building. So, rather than returning a composable expression tree, it returns the actualEmployees
objects.因此,既然有了扩展方法,就可以在程序中使用它了。
哦,同样,在这个例子中,我假设Employees类的以下定义
You can use
bool
argument to verify if the phone number should benull
or not.Also the
Where
method returnsIEnumerable
, there is no explicit converstion toICollection
, thus I changed the method's declaration