简体   繁体   中英

How to convert T object to IEnumerable<T>

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM