Home > Back-end >  How to convert T object to IEnumerable<T>
How to convert T object to IEnumerable<T>

Time:08-28

I have following method

public static IRuleBuilderOptions<T, Guid> MustExistInDatabase<T, TEntity>
    (
        this IRuleBuilder<T, Guid> ruleBuilder,
        TEntity obj
    ) where TEntity : class
{
    if (obj == null)
        return ruleBuilder.Must(id => false)
            .WithMessage("'{PropertyName}' {PropertyValue} not found.");

    var isCollection = obj.GetType().GetInterface(nameof(IEnumerable)) != null;

    if (isCollection)
    {
        var list = (obj as IEnumerable<TEntity>); //I get a null here
        
        if (list.Count() == 0)
        {
            //rest of code
        }
    }
    else
    {
        //rest of code
    }
}

I want to check whether obj is an IEnumerable or not, if it's an IEnumerable, then I want to convert obj into IEnumerable<T>, but I'm getting null when doing (obj as IEnumerable<TEntity>). What is the correct syntax to do this?

CodePudding user response:

You could use the is operator, the combines a type-check and an assignment:

if (obj is IList<TEntity> list)
{
    if (list.Count == 0)
    {
        //rest of code
    }
}

If the obj can be cast to IList<TEntity>, the list variable is assigned to the converted result. This feature is available from C# 7.0 and later.

  • Related