微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 扩展方法,T的Func和T的列表

我想编写一个函数,可以在将值插入List之前完成一些检查.
例如:
class Person {
    public string Name { get; set; }
    public int Value { get; set; }
    public Guid Id { get; set; }
}
-------
var persons = new List<Person>();
// add a new person if John doesn't exist
persons.AddIf(s => !s.Name.Equals("John"),new Person { ... });
----
public static void AddIf(this List<T> lst,Func<T,bool> check,T data)
{
     // how can I use the Func 'check' to check if exist an object with the
     // information that the client wrote and,if not exists,insert the new value
     // into the list???
     if ( check )
}

如何使用Func’check’检查是否存在具有客户端写入信息的对象,如果不存在,则将新值插入列表中?

解决方法

您需要使您的方法通用.
public static void AddIf<T>(this List<T> lst,T data)
{
    if (!lst.All(check))
        return;

    lst.Add(data);
}

和你想要的用法(所有项目都应该满足谓词):

persons.AddIf(s => !s.Name.Equals("John"),new Person { ... });

原文地址:https://www.jb51.cc/csharp/243978.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐