如何在 C# 中传递谓词以函数

本文关键字:谓词 函数 | 更新日期: 2023-09-27 18:33:40

我有:

 public void InitializeStatusList(DropDownList list)
    {
       var dictionaryEntries = GetEntriesFromDatabase();
       list.DataSource = dictionaryEntries.Where(entry => entry is EntryStatus1 || entry is EntryStatus2);
       list.DataBind();           
    }

我有很多这样的功能。我想编写带有作为谓词传递dictionaryEntries查询条件的通用函数。

例如:

public void InitializeStatusList(DropDownList list)
{
    CommonInitializeStatusList(DropDownList list, entry => entry is EntryStatus1 || entry is EntryStatus2);
}
public void CommonInitializeStatusList(DropDownList list, ??????????????? predicate)
{                       
    var dictionaryEntries = GetEntriesFromDatabase();
    list.DataSource = dictionaryEntries.Where(predicate);
    list.DataBind();        
}

什么代表???????????????

提前致谢

如何在 C# 中传递谓词以函数

Func<Entry, bool> predicate应该可以工作,其中Entryentry变量的类型。

你可以这样做:

public void InitializeStatusList(DropDownList list)
{    
    Func<Entry,bool> predicate=entry=>entry is EntryStatus1 || entry is EntryStatus2;
    CommonInitializeStatusList(list, predicate);
}
public void CommonInitializeStatusList(DropDownList list, Func<Entry,bool> predicate)
{                                 
    var dictionaryEntries = GetEntriesFromDatabase();    
    list.DataSource = dictionaryEntries.Where(predicate);
    list.DataBind();
}