pidde2
pidde2

Reputation: 11

Convert IEnumerable<T> into a List<SomeObject>

So I'm building a small application in C# where I have an IEnumerable that I want to cast into a List. This is what I got:

var enumerable = SettingsManager.ReadSettings();
var list = enumerable.Cast<Setting>().ToList();

The compiler says that ReadSettings cannot be inferred from the usage. This is how ReadSettings look like:

public static IEnumerable<T> ReadSettings<T>()
{
     //Code omitted
     return JsonConvert.DeserializeObject<T[]>(fileAsString).ToList<T>();
}

Upvotes: 1

Views: 99

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

If your method is generic, you should provide a generic type-parameter. From your usage I suppose you´re after the type Setting, so your correct code was something like this:

var enumerable = SettingsManager.ReadSettings<Setting>();
var list = enumerable.ToList();

Now enumerable has a strong type known at compile-time, which is why you can omit casting every element within that list to the Setting-type.

If you don´t know the actual type at runtime you´re stuck on using reflection as mentioned in this post.

EDIT: As your ReadSettings-method actually produces a list by calling ToList you could omit the explicit second ToList-call on the second line and cast to List<T> instead. Alternativly - and imho better - was to omit that call within ReadSettings.

Upvotes: 7

Pavel P&#225;ja Halbich
Pavel P&#225;ja Halbich

Reputation: 1583

You are missing T specification for ReadSetting. You need code like this:

var list= SettingsManager.ReadSettings<Setting>();
// continue here

Upvotes: 4

Related Questions