如何在C#中将IEnumerable转换为IList?

时间:2013-07-27 14:09:33

标签: 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?)

1 个答案:

答案 0 :(得分:3)

在这种情况下,您不能将查询返回的对象 IList<T>,因此转换会失败。

最简单的解决方法就是调用Enumerable.ToList,它会从中创建List<T>

return topicSubTopicsSelect.ToList();

顺便说一下,如果您在之前的查询中调用了AsEnumerable(),则ToList来电是毫无意义的(尽管您可以使用AsEnumerable() 代替 ToList() - 你无论如何都不需要两个单独的查询。我会使用:

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();