分组和排序半写Lambda查询

时间:2018-05-14 16:56:06

标签: c# asp.net linq lambda

public class Car
{
    [JsonProperty("name")]
    public string Name{get;set;}
    [JsonProperty("type")]
    public string Type{get;set;}
}

public class CarOwner
{
    [JsonProperty("name")]
    public string Name{get;set;}
    [JsonProperty("gender")]
    public string Gender{get;set;}
    [JsonProperty("age")]
    public int Age{get;set;}
    [JsonProperty("cars")]
    public List<Car> Cars{get;set;}
}

public class Result
{
    public string Gender { get; set; }
    public List<string> Name { get; set; }
}

我尝试过:

var z = m.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()});

我需要按性别进行分组,并按字母顺序排列显示其下的所有汽车名称。 e..g

男性: 大使(按照白名单排序) 兰博基尼 马鲁蒂

女: 布加迪(按字母顺序排序) 马鲁蒂 Scooty

1 个答案:

答案 0 :(得分:0)

You already know what you need to do, and this is exactly what you need.

 var res = owners
             .GroupBy(o => o.Gender)
             .Select(r => new Result
         {
             Gender = r.Key,
             Name = r
             .SelectMany(co => co.Cars)
             .Select(c => c.Name)
             .OrderBy(car => car).ToList()
         });