C# extension methods on Codeplex
A post on Codeplex’s ExtensionOverflow forum encourages users to share their favorite C# extension methods. One notable submission came from a user who provided a In
method for checking list membership.
In extension method
In
The code of the extension method is as follows:
public static bool In<T>(this T source, params T[] list) { if(source == null) throw new ArgumentNullException("source"); return list.Contains(source); }
Examples of usage
This extension method provides a concise way to check whether a value is contained in a list. For example, instead of writing a multi-line conditional statement to check for a specific value, you can simply use the In
method:
if (reallyLongIntegerVariableName.In(1, 6, 9, 11)) { // 执行某些操作... } if (reallyLongStringVariableName.In("string1", "string2", "string3")) { // 执行某些操作... } if (reallyLongMethodParameterName.In(SomeEnum.Value1, SomeEnum.Value2, SomeEnum.Value3, SomeEnum.Value4)) { // 执行某些操作... }
This method simplifies your code by eliminating the need for lengthy conditional statements, making your code easier to read and maintain. It is available in the Codeplex ExtensionOverflow project for users who wish to incorporate it into their projects.
The above is the detailed content of Does C# Need an 'In' Extension Method for List Membership Checks?. For more information, please follow other related articles on the PHP Chinese website!