Generic Extension Method to Determine if a Value is Contained in a List or Array of Elements
Posted: 7/9/2021 11:11:52 AM
By: PrintableKanjiEmblem
Times Read: 1,369
0 Dislikes: 0
Topic: Programming: .NET Framework

Why something like this isn't built into .NET, I have no idea. But several places I've worked at have had variations on this to make development easier. So here's my implementation of it:

using System.Collections.Generic;
using System.Linq;

namespace [ProjectName].ExtensionMethods
{
   public static class GenericExtensions
   {
      /// 
      /// Indicates if the source value is contained in the passed list.
      /// 
      /// Source value we are looking for in the list.
      /// List of values to search.
      /// bool
      public static bool IsContainedIn(this T sourceValue, IEnumerable list)
      {
         return list.Contains(sourceValue);
      }

      /// 
      /// Indicates if the source value is contained in the passed params.
      /// 
      /// 
      /// Source value we are looking for in the list
      /// Param array of values to search.
      /// bool
      public static bool IsContainedIn(this T sourceValue, params T[] list)
      {
         return list.Contains(sourceValue);
      }
   }
}

Usage examples:

using ContainedTest.ExtensionMethods;
using System;
using System.Collections.Generic;
 
namespace ContainedTest
{
   class Program
   {
      static void Main()
      {
         ExampleWithList();
         ExampleWithParams();
 
         Console.Write("Press Enter");
         Console.ReadLine();
      }
 
      private static void ExampleWithList()
      {
         var sourceValue = 3;
         var valueList = new List { 1, 2, 3, 4, 5, 6, 7, 8 };
 
         Console.WriteLine("Example with List:");
 
         Console.WriteLine($"Is 3 contained in value list: {sourceValue.IsContainedIn(valueList)}");
         Console.WriteLine($"Is 22 contained in value list: {22.IsContainedIn(valueList)}");
         Console.WriteLine($"Is 3 contained in inline-supplied list: {sourceValue.IsContainedIn(new List { 2, 3, 7, 22 })}");
 
         Console.WriteLine();
      }
 
      private static void ExampleWithParams()
      {
         Console.WriteLine("Example with Params:");
 
         var sourceValue = 3;
         Console.WriteLine($"Is 3 contained in param array: {sourceValue.IsContainedIn(1, 3, 5, 7, 9)}");
         Console.WriteLine($"Is 22 contained in param array: {22.IsContainedIn(1, 3, 5, 7, 9)}");
 
         Console.WriteLine();
      }
   }
}

Enjoy!

Rating: (You must be logged in to vote)