ExtensionMethod.NET Home of 855 C#, Visual Basic, F# and Javascript extension methods

AnyOfType

Determines if there is an element of a given type inside a collection.

Source

namespace System.Collections;

public static class EnumerableExtensions
{
    /// <summary>
    /// Determines if there is an element of type <typeparam name="T"> </typeparam> inside a <see cref="IEnumerable" />.
    /// </summary>
    /// <typeparam name="T">Actual type to look for</typeparam>
    /// <param name="source">Source collection.</param>
    /// <returns>True if there is an element whose type is <typeparam name="T"/></returns>
    public static bool AnyOfType<T>(this IEnumerable source)
    {
        foreach (var obj in source)
        {
            if (obj is T)
            {
                return true;
            }
        }

        return false;
    }
}

Example

object[] myList = new object[]
{
    "Hello",
    1,
    new StringBuilder()
};
	
Console.WriteLine(myList.AnyOfType<string>()); // Returns true
Console.WriteLine(myList.AnyOfType<bool>()); // Returns false

Author: Maxime Poulain

Submitted on: 22 jun 2022

Language: csharp

Type: System.Collections.IEnumerable

Views: 2391