[英]How can I cast IEnumerable<?> to IEnumerable<string>?
[英]How can I cast an IEnumerable to an IList in C#
我有以下几点:
public IList<TopicSubTopic> GetTopicSubTopics(int topicId)
{
var topicSubTopics = _subTopicsRepository
.GetAll()
.Where(s => s.TopicId == topicId)
.Include(s => s.Topic)
.ToList();
var topicSubTopicsSelect = from item in topicSubTopics.AsEnumerable()
select new TopicSubTopic(
item.TopicId,
item.SubTopicId,
item.Topic.Name,
item.Name);
return topicSubTopicsSelect;
}
和:
public partial class TopicSubTopic
{
public TopicSubTopic(int topicId, int subTopicId, string topicName, string subTopicName)
{
TopicId = topicId;
SubTopicId = subTopicId;
TopicName = topicName;
SubTopicName = subTopicName;
}
public int TopicId { get; set; }
public int SubTopicId { get; set; }
public string TopicName { get; set; }
public string SubTopicName { get; set; }
}
我的IDE给我以下消息:
Error 3 Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<Models.Views.TopicSubTopic>' to
'System.Collections.Generic.IList<Models.Views.TopicSubTopic>'.
An explicit conversion exists (are you missing a cast?)
你不能在这种情况下-通过查询返回的对象不会是一个IList<T>
所以投将失败。
最简单的解决方法是调用Enumerable.ToList
,它将从中创建List<T>
:
return topicSubTopicsSelect.ToList();
AsEnumerable()
鉴于您已经在上一个查询中调用了ToList
,因此您的AsEnumerable()
调用毫无意义(尽管您可以使用AsEnumerable()
而不是 ToList()
,而且您也不需要两个单独的查询。 d使用:
return _subTopicsRepository
.GetAll()
.Where(s => s.TopicId == topicId)
.Include(s => s.Topic)
.AsEnumerable()
.Select(item => new TopicSubTopic(item.TopicId,
item.SubTopicId,
item.Topic.Name,
item.Name))
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.