-1

我有构造函数

class MyClass
{
    public MyClass(IReportGroup reportGroup, Func<..., bool> filter)
    {
         reportGroup.Reports.Where(filter).ToList().ForEach(r => ... )
    }
}

调用:new MyClass(reportGroup, () => reports.Where(r=>r.ID != 0))

4

3 回答 3

1

这个问题有点不清楚,但我想你想要实现的是传递要在 Where 方法中使用的过滤器表达式?您可以通过传递Func<T, bool>whereT是列表中找到的对象类型来做到这一点。我整理了一个小示例程序,展示了这一点:

public class Person
{
    public string Name { get; set; }
}

public class Program
{
    private static void Main(string[] args)
    {
        IEnumerable<Person> persons = GetPersons();

        // invoke the method, passing a filter expression to be used
        PrintFiltered(persons, p => p.Name.StartsWith("F"));
    }

    private static void PrintFiltered(IEnumerable<Person> persons, Func<Person, bool> filter)
    {
        // use the expression to filter the sequence
        foreach (Person person in persons.Where(filter))
        {
            Console.WriteLine(person.Name);
        }
    }

    private static IEnumerable<Person> GetPersons()
    {
        return new[]
            {
                new Person { Name = "Fredrik" },
                new Person { Name = "John" },
                new Person { Name = "Steven" },
            };
    }
}

要在构造函数中接受过滤器,并且还有一个默认过滤器(将返回完整序列),您可以这样做:

class MyClass
{
    public MyClass() : this(p => true) { }

    public MyClass(Func<Person, bool> filter)
    {
        // do work
    }
}        
于 2012-11-13T11:56:26.557 回答
0

我猜你想将过滤器表达式作为参数传递给你的构造函数。您必须只传递您在where函数中编写的 lambda,并在参数类型定义中指定报告集合元素的类型:

public MyClass(IReportGroup reportGroup, Expression<Func<Report, bool>> filter)

并像这样调用它:

new MyClass(reportGroup, r => r.ID != 0)
于 2012-11-13T11:50:38.743 回答
0

这就是你想要的——

  new MyClass(reportGroup, r => r.ID != 0)
于 2012-11-13T11:56:01.477 回答