user1943020
user1943020

Reputation:

How can I cast an IEnumerable to an IList in C#

I have the following:

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;
}

and:

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; }
}

My IDE is giving me the following message:

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?)

Upvotes: 0

Views: 1755

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

You can't, in this case - the object returned by the query won't be an IList<T>, so a cast would fail.

The simplest fix is just to call Enumerable.ToList, which will create a List<T> from it:

return topicSubTopicsSelect.ToList();

As an aside, your AsEnumerable() call is pointless given that you've already called ToList in the previous query (although you could use AsEnumerable() instead of ToList() - and you don't need two separate queries anyway. I'd use:

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

Upvotes: 3

Related Questions