简体   繁体   中英

Cast List<object> to IEnumerable<T> within Generic Task

I have a generic task where I am using a List<object> to add objects of type specified in the task.

I would like to return this list by casting it from list<object> to IEnumerable<T> within the task. Is this possible.

Appreciate any help!

public List<Object> Contactcollection { get; set; }

Task<IEnumerable<T>> GetAllEntityRecords<T>(string URI, string authorization) where T : new()
{

    JEnumerable<JToken> children = Raw.Children();
    Contactcollection = new List<object>();
    foreach (JToken child in children)
    {
        T _contact = new T();
        _contact = JsonConvert.DeserializeObject<T>(child.ToString());

        Contactcollection.Add(_contact);
    }

    return (IEnumerable<T>)Contactcollection;
}

You can use OfType<T> LINQ extension to filter the collection for only the instances of T .

Contactcollection.OfType<T>();

However, instead of List<object> you can just use List<T> in this case and avoid all the casting :-) .

Task<IEnumerable<T>> GetAllEntityRecords<T>(string URI, string authorization) where T : new()
{

    JEnumerable<JToken> children = Raw.Children();
    var results = new List<T>();
    foreach (JToken child in children)
    {            
        var result = JsonConvert.DeserializeObject<T>(child.ToString());

        results.Add(result);
    }
    Contactcollection = new List<object>(results.OfType<object>());
    return results;
}

The question is why does your Contactcollection property have type of List<object> however. If you know it is going to contain contacts, why not use explicit typing instead of generics? And if it is not, it would be better to name it differently and then just assign it at the end of the method if you need to store it, as I demonstrated at the end of my sample.

Finally note that you don't have to create a new instance of T before deserializing. JsonConvert will instantiate the type automatically.

You can do this quite simply with LINQ. There's no need to store the results in a list:

IEnumerable<T> GetAllEntityRecords<T>(string URI, string authorization)
{
  return Raw.Children().Select(child => JsonConvert.DeserializeObject<T>(child.ToString());
}

But if you prefer to store them in a list for some reason, you can add a .ToList() to the end of that expression.

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