简体   繁体   中英

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

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM