Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method, Func of T and List of T

I would like to code a function that can accomplish some check before insert a value into a List. For example:

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 )
}

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?

like image 540
Gaetanu Avatar asked Nov 14 '12 06:11

Gaetanu


1 Answers

You need to make your method generic.

public static void AddIf<T>(this List<T> lst, Func<T, bool> check, T data)
{
    if (!lst.All(check))
        return;

    lst.Add(data);
}

And usage like you wanted (all items should satisfy predicate):

persons.AddIf(s => !s.Name.Equals("John"), new Person { ... });
like image 107
Sergey Berezovskiy Avatar answered Sep 20 '22 23:09

Sergey Berezovskiy