加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:32:59 所属栏目:百科 来源:网络整理
导读:我想编写一个函数,可以在将值插入List之前完成一些检查. 例如: class Person { public string Name { get; set; } public int Value { get; set; } public Guid Id { get; set; }}-------var persons = new ListPerson();// add a new person if John doesn
我想编写一个函数,可以在将值插入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 { ... });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读