Skip to content

Commit

Permalink
add Collection<T>.ContainsAny extension method
Browse files Browse the repository at this point in the history
  • Loading branch information
radj307 committed Sep 20, 2023
1 parent 5e26821 commit c401f64
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions VolumeControl.TypeExtensions/CollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,48 @@ public static int AddRangeIfUnique<T>(this ICollection<T> collection, IEnumerabl
}
return count;
}
/// <summary>
/// Determines whether the <paramref name="collection"/> contains at least one of the specified <paramref name="items"/>.
/// </summary>
/// <typeparam name="T">Item type contained within the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="items">The items to search for in the collection.</param>
/// <returns><see langword="true"/> when at least one of the specified <paramref name="items"/> exists in the <paramref name="collection"/>; otherwise <see langword="false"/>.</returns>
public static bool ContainsAny<T>(this ICollection<T> collection, params T[] items)
{
switch (items.Length)
{
case 0: // no search items specified:
return collection.Count > 0;
case 1: // one search item specified:
return collection.Contains(items[0]);
default: // multiple search items specified:
{
bool itemsContainsNull = false;
for (int i = 0; i < items.Length; ++i)
{
if (items[i] == null) itemsContainsNull = true;
}

foreach (var item in collection)
{
if (item == null)
{
if (itemsContainsNull) return true;
else continue;
}

for (int i = 0; i < items.Length; ++i)
{
if (item.Equals(items[i]))
{
return true;
}
}
}
return false;
}
}
}
}
}

0 comments on commit c401f64

Please sign in to comment.