订购记录的组别[英] Ordering Group of records

本文是小编为大家收集整理的关于订购记录的组别的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在使用以下类

class Country
{
   string CtryID {get; set;}
   List<City> city {get; set;}
}

class City
{
   string county {get; set;}    
   int sqkm {get; set;}
}

我想订购这样的结果

这是国家和城市的一些示例数据

国家

美国
英国
加拿大

城市

CityC
CityF
城市A
城市B
城市G
城市D
城市E

我想按国家和城市排序记录(假设一些城市属于各自的国家)并像这样打印它们

加拿大城市A城市B城市E

英国城市G城市F

美国城市C城市D

等等

推荐答案

很大程度上取决于您使用的技术如何显示它.例如,您使用的是 ASP.NET 网站、Windows 窗体还是控制台应用程序.您使用的是 O/RM 工具还是内存中的集合.下面是一个在控制台应用程序中使用内存对象和 LINQ 的示例:

IEnumerable<Country> countries = GetCountries();

foreach (var country in countries.OrderBy(c => c.Name))
{
    Console.Write(country.Name + " ");

    foreach (var city in country.Cities.OrderBy(c => c.Name))
    {
        Console.Write(city.Name + " ");
    }

    Console.WriteLine();
}

请注意,我为此更改了您的对象模型.A 给 Country 一个 Name 属性,给 City 一个 Name 属性并将 city 属性重命名为 Cities.


你也可以这样做:

var countriesNames =
    from country in countries
    order by country.Name
    let cityNames = country.Cities.OrderBy(c => c.Name).ToArray()
    select new
    {
        Name = country.Name
        Cities = string.Join(" ", cityNames)
    }

foreach (var country in countriesNames)
{
    Console.WriteLine(country.Name + " " + country.Cities);
}

本文地址:https://www.itbaoku.cn/post/1556864.html

问题描述

I am using the following class

class Country
{
   string CtryID {get; set;}
   List<City> city {get; set;}
}

class City
{
   string county {get; set;}    
   int sqkm {get; set;}
}

I want to order the result like this

Here's is some sample data for Country and City

Country

US
UK
Canada

City

CityC
CityF
CityA
CityB
CityG
CityD
CityE

I want to order the records by Country and then City (assuming some cities belong to respectivce countries) and print them like this

Canada CityA CityB CityE

UK CityG CityF

US CityC CityD

and so on

推荐答案

It depends a lot on the technology you use how to display this. For instance, are you using a ASP.NET web site, Windows Forms or Console Application. Are you using a O/RM tool or in-memory collection. Here is an example using in-memory objects, with LINQ, in a Console Application:

IEnumerable<Country> countries = GetCountries();

foreach (var country in countries.OrderBy(c => c.Name))
{
    Console.Write(country.Name + " ");

    foreach (var city in country.Cities.OrderBy(c => c.Name))
    {
        Console.Write(city.Name + " ");
    }

    Console.WriteLine();
}

Please note that I changed your object model for this. A gave Country a Name property, gave City a Name property and renamed the city property to Cities.


You can also do this:

var countriesNames =
    from country in countries
    order by country.Name
    let cityNames = country.Cities.OrderBy(c => c.Name).ToArray()
    select new
    {
        Name = country.Name
        Cities = string.Join(" ", cityNames)
    }

foreach (var country in countriesNames)
{
    Console.WriteLine(country.Name + " " + country.Cities);
}