Lambda查询有助于分组和排序。 [英] Lambda query help with grouping and ordering.

查看:106
本文介绍了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; }
    }





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



男:

大使(按照白名单排序)

兰博基尼

Maruti



女:

布加迪(按字母顺序排序)

Maruti

Scooty



我尝试过:





I need to group by gender and display all names of cars under it in alphabetically sorted order. e..g

Male:
Ambassador (sorted albhabetically)
Lamborghini
Maruti

Female :
Bugatti (sorted alphabetically)
Maruti
Scooty

What I have tried:

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()});
		var o= z.OrderBy(l=>l.Name).GroupBy(p=>p.Gender);

推荐答案

var results = owners.Where(b => b.Cars != null)
     .GroupBy(o => o.Gender, o => o.Cars, (key, g) =>
  new Result { Gender = key, Name = g.SelectMany(cars => cars)
      .Select(car => car.Name).Distinct().OrderBy(k => k).ToList() });



我忘记了汽车名称的订单。



这里我添加了Where子句这将删除使用空车的所有者。


I forgot the order by for car names.

Here I added the Where clause that will remove owners with null cars.


对象的结构(Car和CarOwner)阻止你得到你想要的东西(没有额外的编码)。首先,您不应该尝试在一行代码中执行所有操作。这不是不可能的,这是不好的做法,因为它很难维护。



添加这个类:

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;
    }
}





您的使用情况将如下所示(所有者定义为 List< CarOwnerCar> ,并在反序列化JSON数据时填充):



And your usage will look like this (owners is defined as List<CarOwnerCar>, and is populated when you deserialize your JSON data):

// get all of the car owners with at least one "heavy" car
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();

// now get all the cars for all of the car owners, as well as the gender of the owner
List<GenderCar> gendercars = new List<GenderCar>();
foreach (Result res in cars)
{
    gendercars.AddRange(res.GetCars());
}

// sort the gender cars list by gender (descending, because your requirements 
// indicated that male owners be listed first), and then by car name
gendercars = gendercars.OrderByDescending(x=>x.Gender).ThenBy(x=>x.CarName).ToList();

// display the results
string gender = string.Empty;
foreach (GenderCar car in gendercars)
{
    // if the gender changes, perform some special output indicating the 
    // current gender being processed
    if (gender != car.Gender)
    {
        gender  = car.Gender;
        Console.WriteLine(gender+":");
    }

    // output the car name
    Console.WriteLine("    "+car.CarName);
}

Console.ReadKey();





最后注释 - 您的变量命名可以使用一些工作。



编辑===========================



您坚持使用过于复杂的Linq语句会妨碍您继续使用代码。在现实世界的开发中,您的经理会对您错误地优化代码的努力感到非常恼火。简单,使其可维护。这是开发人员成功的关键。



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.


这篇关于Lambda查询有助于分组和排序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆