The structure of your objects (Car and CarOwner) prevents you from getting what you want (without additional coding). First, you shouldn't try to do everything in one line of code. IT's not that it's not possible, it's that it's bad practice because it is HIGHLY unmaintainable.
Add this class:
public class GenderCar
{
public string Gender { get; set; }
public string CarName { get; set; }
}
Modify this class (add the new method)
public class Result
{
public string Gender { get; set; }
public List<string> Name { get; set; }
public List<GenderCar> GetCars()
{
List<GenderCar> gc = new List<GenderCar>();
foreach(string name in Name)
{
gc.Add(new GenderCar(){Gender = this.Gender, CarName = name});
}
return gc;
}
}
And your usage will look like this (
owners
is defined as
List<CarOwnerCar>
, and is populated when you deserialize your JSON data):
List<Result> cars = owners.Where(b => b.Cars != null).Select(k =>
new Result{Gender = k.Gender, Name = k.Cars.Where(t => t.Type.Contains("Heavy")).Select(h => h.Name).ToList()}).ToList();
List<GenderCar> gendercars = new List<GenderCar>();
foreach (Result res in cars)
{
gendercars.AddRange(res.GetCars());
}
gendercars = gendercars.OrderByDescending(x=>x.Gender).ThenBy(x=>x.CarName).ToList();
string gender = string.Empty;
foreach (GenderCar car in gendercars)
{
if (gender != car.Gender)
{
gender = car.Gender;
Console.WriteLine(gender+":");
}
Console.WriteLine(" "+car.CarName);
}
Console.ReadKey();
Final note - your variable naming could use some work.
EDIT ===========================
Your insistence on using overly complex Linq statements is preventing you from moving on in the code. In real world development, your manager will become quite annoyed with your efforts to falsely optimize the code. Make it simple, which makes it maintainable. That's the ultimate key to success as a developer.