If I have a list inside a class inside of a list where the classes are defined like so:
class Class1
{
public int Id { get; set; }
public List<Class2> Class2s { get; set; }
}
class Class2
{
public string Name { get; set; }
public string Value { get; set; }
}
I can create a list of a class of type Result
where Result
is:
class Result
{
public int Class1Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Note that the Result
class contains values from Class1
and Class2
.
Like so:
var results = new List<Result>();
foreach (var class1 in class1s) //class1s is a List of Class1
{
foreach (var class2 in class1.Class2s)
{
results.Add(new Result()
{
Class1Id = class1.Id,
Name = class2.Name,
Value = class2.Value,
};
}
}
How can I do this via a linq query?
I have tried the following:
IList<Result> list = class1s.Select(c => c.Class2s.Select(c2 => new Result()
{
Class1Id = c.Id,
Type = c2.Type,
Name = c2.Name,
}).ToList()).ToList();
But this fails with the error:
Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<Results>' to 'System.Collections.Generic.IList<Results>'. An explicit conversion exists (are you missing a cast?)
NOTE:
The duplicates do not answer the question as they do not address the issue when the resultant list is a list of the inner classes AND using a property of the inner class.