b85411 b85411 - 4 months ago 16
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

List<Config>
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
List<Config>
?

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));
lc.add(config);
}


Thank you for your time

Answer
var configs = 
    Directory
    .GetFiles(PATH, "*.*", SearchOption.AllDirectories)
    .Where(s => s.Contains(CONFIG_NAME))
    .Select(x => JsonConvert.DeserializeObject<Config>(File.ReadAllText(x)));