For your own semantics, you have an answer to rely on. But for me, the naming method is misleading, the more I think about it. AddIf means add, if any, or add if all? In your case, that's all. Therefore, you should name it better. AddIfAll or something like that.
To add to the list, if something does not exist, this is a general requirement, and what I would like to offer is something even more complex (I think) for your purpose, which makes it easier for the subscriber.
May be
public static bool AddIfNotContains<S, T>(this ICollection<S> lstObject, Func<S, T> selector, T valueToMatch, S objectToAdd) { if (lstObject.Contains(selector, valueToMatch)) return false; lstObject.Add(objectToAdd); return true; }
A little Contains overload, which I prefer to use in my programs:
public static bool Contains<S, T>(this IEnumerable<S> lstObject, Func<S, T> comparer, T valueToMatch) { return lstObject.Any(s => comparer(s).Equals(valueToMatch)); }
This allows us to avoid problems with recording the Equals statement from our side each time.
You may call:
persons.AddIfNotContains(s => s.Name, "John", new Person { ... });
I think the syntax is much simpler.
Note:
I hope you know about that. You can write very well
persons.AddIfNotContains(s => s.Name, "John", new Person { Name = "Serena", .. });
, even if someone already exists with the name Serena , because here you check John . If it is good for you, good and good. The best implementation, if I understand your problem correctly, would be :
public static bool AddIfTrulyNotContains<S, T>(this ICollection<S> lstObject, Func<S, T> selector, S objectToAdd) { if (lstObject.Contains(selector, selector(objectToAdd))) return false; lstObject.Add(objectToAdd); return true; }
Now you can easily call:
persons.AddIfTrulyNotContains(s => s.Name, new Person { Name = "John", .. });
This simply checks John and adds if John is not on the list. In addition, I made a return type for bool to indicate the addition.