【问题标题】:How to call generic method like Find, FindAll如何调用 Find、FindAll 等泛型方法
【发布时间】:2020-03-14 10:49:00
【问题描述】:

我是中级 C# 开发人员。我正在尝试在我的程序中实现一些方法。但它一直在给不眠之夜。例如 注意:我已经提前声明了类属性。

Employee employe = new Employee(){
    ID = 111,
    Name = "Eric Trump",
    Gender = "Male",
    Salary = 900000
};
Employee employe2 = new Employee()
{
    ID = 112,
    Name = "Ayo",
    Gender = "Female",
    Salary = 8900
};

List<Employee> listemp = new List<Employee>();
listemp.Add(employe);
listemp.Add(employe2);

如何使用FindFindAll()FindLast()

【问题讨论】:

    标签: c# .net list generics


    【解决方案1】:

    您可以通过将Predicate&lt;T&gt; 委托传递给FindFindLastFindAll 方法来做到这一点

    List<Employee> listemp = new List<Employee>();
    listemp.Add(employe);
    listemp.Add(employe2);
    
    var result = listemp.FindLast(e => e.ID == 112); //or listemp.Find(e => e.ID == 112)
    

    e =&gt; e.ID == 112 被称为 lambda 表达式,它只是指定匿名委托的一种更方便的方式,您可以在Delegates and lambdas 找到更多详细信息

    【讨论】:

    • 好的。 find() 方法呢?
    • @GbolahanEfunkoya 对于Find 方法也是如此,它接受相同的谓词作为参数
    • 谢谢您,先生。我很感激。我们可以在社交平台上连接吗?你的把柄。 Instagram、推特等
    • @GbolahanEfunkoya 欢迎您,如果它解决了您的问题并在将来帮助其他人,您可以批准一个答案。嗯,我觉得这个平台对于编程相关的问题来说已经足够了:)
    【解决方案2】:

    只需使用 lambda 表达式:

    List<string> lists = new List<string>()
    {
        "1", "2", "3"
    };
    var all = lists.FindAll(s => s == "1");
    

    Read more about Find all here.

    更新:

    Lambda-expression is a shorter way to represent anonymous methods. 所以你可以这样使用它们:

    List<Employee> employees = new List<Employee>()
    {
        new Employee(){
           Id = 111,
           Name = "Eric Trump",
           Gender = "Male",
           Salary = 900000
        },
        new Employee(){
            Id = 112,
            Name = "Ayo",
            Gender = "Female",
            Salary = 8900
        }
    };
    
    var findAll = employees.FindAll(s => s.Id == 111);
    var findLast = employees.FindLast(s => s.Id == 111);
    var find = employees.Find(s => s.Id == 111);
    

    【讨论】:

    • 谢谢。工作正常
    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多