[英]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. 我有一个通用任务,其中我使用
List<object>
添加任务中指定类型的对象。
I would like to return this list by casting it from list<object>
to IEnumerable<T>
within the task. 我想通过将该列表从
list<object>
强制转换为IEnumerable<T>
来返回此列表。 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
. 您可以使用
OfType<T>
LINQ扩展仅对T
的实例进行过滤。
Contactcollection.OfType<T>();
However, instead of List<object>
you can just use List<T>
in this case and avoid all the casting :-) . 但是,在这种情况下,您可以只使用
List<T>
来代替List<object>
,并避免所有强制转换:-)。
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. 问题是,为什么您的
Contactcollection
属性具有List<object>
类型。 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. 最后请注意,在反序列化之前不必创建
T
的new
实例。 JsonConvert
will instantiate the type automatically. JsonConvert
将自动实例化类型。
You can do this quite simply with LINQ. 您可以使用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. 但是,如果由于某种原因您希望将它们存储在列表中,则可以在该表达式的末尾添加
.ToList()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.