首页 > 解决方案 > 我可以为 IEnumerable.Any 方法动态添加参数到 LINQ 查询吗?

问题描述

我创建了一个接受动态列表、对象和两个参数名称的方法。我想使用 Enumerable.Any 方法返回一个布尔值,该方法具有基于传递给 mehtod 的参数名称的匹配条件。

public static bool CheckDuplicate(List<T> list, Object obj, string param1, string param2)
{
    return list.Any(item => item.pararm1 = obj.param1 && item.param2 = obj.param2);
}

我想根据动态提供的条件找到与 obj 对象的值匹配的项目。

标签: c#linq

解决方案


考虑创建一个类似 LINQ 的扩展方法WhereAll,它执行Where作为参数给出的所有谓词中的一个:

static IEnumerable<TSource> WhereAll<TSource>(this IEnumerable<TSource> source
   IEnumerable<Func<TSource, bool>> predicates)
{
    // TODO: exception if source / predicates null

    // return all source elements that have a true for all predicates:
    foreach (var sourceElement in source)
    {
        // check if this sourceElement returns a true for all Predicates:
        if (predicates.All(predicate => predicate(sourceElement))
        {
             // yes, every predicate returns a true
             yield return sourceElement;
        }
        // else: no there are some predicates that return false for this sourceElement
        // skip this element
 }

用法:

List<Person> persons = ...
// Get all Parisians with a Name that were born before the year 2000:
var result = persons.WhereAll(new Func<Person, bool>[]
    {
         person => person.Name != null,
         person => person.BirthDay.Year < 2000,
         person => person.Address.City == "Paris",
    });

推荐阅读