b85411 b85411 - 1 year ago 79
C# Question

Convert foreach to be part of LINQ query (C#)

I currently have a LINQ query to get some JSON files and then I run a foreach loop to convert the JSON into an object. Ultimately I want to have a

which I can work from.

Is there any way I can combine this into the LINQ query so I've just got the one statement, and files is of type

var files = Directory.GetFiles(PATH, "*.*", SearchOption.AllDirectories).Where(s => s.Contains(CONFIG_NAME));
List<Config> lc = new List<Config>();

foreach (var file in files)
Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText(file));

Thank you for your time

Answer Source
var configs = 
    .GetFiles(PATH, "*.*", SearchOption.AllDirectories)
    .Where(s => s.Contains(CONFIG_NAME))
    .Select(x => JsonConvert.DeserializeObject<Config>(File.ReadAllText(x)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download