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?
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 { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With