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

查看:49
本文介绍了记录的订购组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下课程

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

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

我要订购这样的结果

以下是国家和城市"的一些示例数据

Here's is some sample data for Country and City

国家/地区

美国
英国
加拿大

US
UK
Canada

城市

CityC
CityF
CityA
CityB
CityG
CityD
CityE

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

加拿大 城市A 城市B CityE

Canada CityA CityB CityE

英国 城市G CityF

UK CityG CityF

美国 城市C CityD

US CityC CityD

以此类推

推荐答案

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

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

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

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

这篇关于记录的订购组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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