【问题标题】:c# how to sort nested collectionsc#如何对嵌套集合进行排序
【发布时间】:2021-02-24 05:06:44
【问题描述】:

我可能想太多了,我迷路了。我是 C# 新手,不知道解决这个问题的最佳方法是什么。

string[] input = new string { "FR_Paris", "UK_London", "UK_Bristol" };

控制台中所需的输出按国家/地区城市的出现排序,城市按字母顺序排序。

在这种情况下是:

  • 英国 2x 布里斯托尔,伦敦
  • FR 1x 巴黎

我不会撒谎,这是我的作业。我知道如何解析输入,我认为对于城市来说,必须使用一个可以排序但不知道哪种类型的集合。说到嵌套集合,我有点迷茫。

请至少给我一个方向。

非常感谢!

【问题讨论】:

  • 这能回答你的问题吗? Sort List by occurrence of a word by LINQ C#
  • 首先,计算每个国家,如果它被'_'分隔,你可以拆分字符串获取它的ASCII码并将其存储一个数组,然后从该数组中获取计数(或者你可以使用正则表达式,但我可以将它用于家庭作业有点高级),对于排序,你可以使用 Linq 内置的排序功能
  • FR_ParisUK_LondonUK_Bristol的字符串值是多少?
  • 您正在寻找的数据结构(可能)是Lookup,您可以使用ToLookup() 从数组中创建它。
  • @styx ,好点,对不起。我跳过了“”帖子已编辑

标签: c# sorting collections


【解决方案1】:

试试这个

// Init Array
string[] input = new string[] { "FR_Paris", "UK_London", "UK_Bristol" };

//Get All Codes
List<string> Codes = new List<string>();
foreach (var CityName in input)
{
   var Name = CityName.Split('_')[0]; // Get Name After _ Paris
   if (!Codes.Contains(Name))
      Codes.Add(va);
}

// Print
foreach (var Code in Codes.OrderBy(x => x))
{
   var AllNames = input.Where(x => x.StartsWith(Code + "_")).Select(x => x.Split('_')[1]);

   Console.WriteLine(Code + " " + xd.Count() + "x " + string.Join(",", AllNames.OrderBy(x => x)));
}

【讨论】:

  • 不要提供变量名称,例如 vaxd
  • 另外,你应该在循环外做一次Codes.OrderBy(x =&gt; x),为什么每次都做?
  • Codes.OrderBy(x => x) 不是每次都运行,它只在 foreach 命中时运行一次。
  • 非常感谢你们...我必须按发生率排序:英国 2x 布里斯托尔、伦敦 FR 1x 巴黎但我会做剩下的 :)
【解决方案2】:

你可以试试linq

var input = new List<string> { "FR_Paris", "UK_London", "UK_Bristol" };

var result = input.Select(x => new { Country = x.Split("_")[0], City = x.Split("_")[1] })
                  .GroupBy(x => x.Country)
                  .Select(x => $"{x.Key} {x.Count()}x {String.Join(", ", x.OrderBy(x => x.City).Select(x => x.City))} ");
foreach (var item in result)
{
    Console.WriteLine(item);
}

输出

FR 1x Paris
UK 2x Bristol, London

【讨论】:

    【解决方案3】:

    使用 LINQ:

    var grouped = input
        .Select(x => x.Split('_')) // Split all strings into array[2]
        .GroupBy(x => x[0]) // Group by country
        .OrderByDecending(x => x.Count()); // Order by number of cities
    

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 2011-04-04
      相关资源
      最近更新 更多