如何从C#中的数组中获取最短的国家/地区名称



下面的程序为我提供了字符串数组中最短的国家/地区字符计数。如何使用Linq同时检索最短的国家名称?所以我想检索英国的名字,同时我找到最短的国家字符计数。

class Program
{
    static void Main()
    {
        string[] countries = { "India", "USA", "UK" };
        var minCount = countries.Min(x => x.Length);
        var maxCount = countries.Max(x => x.Length);
        Console.WriteLine
            ("The shortest country name has {0} characters in its name", minCount);
        Console.WriteLine
            ("The longest country name has {0} characters in its name", maxCount);
    }
}

一种简单的方法是按名称Length:对数组进行排序

  string[] countries = { "India", "USA", "UK" };
  var shortestCountry= countries.OrderBy(s=>s.Length).First();

有了shortestCountry,您就拥有了所需的两样东西。

另一种方法可以是使用Aggregate扩展方法:

string[] countries = { "India", "USA", "UK" };
var shortestCountry = chrs2.Aggregate((seed, e) => seed.Length < e.Length ? seed :  e);

只需按名称长度排序所有国家,并取第一个(最短)和最后一个(最长):

string[] countries = { "India", "USA", "UK" };
var ordered = countries.OrderBy(x => x.Length);
var min = ordered.First();
var max = ordered.Last();
//"The shortest country name is UK, it has 2 characters in its name"
Console.WriteLine("The shortest country name is {0}, it has {1} characters in its name",
    min, min.Length);
//"The longest country name is India, it has 5 characters in its name"
Console.WriteLine("The longest country name is {0}, it has {1} characters in its name",
    max, max.Length);

我知道这个问题已经有了一个公认的答案,这个答案对于给定的具体例子来说是完全合适的,但其他阅读本文的人应该记住,它没有达到应有的规模。OrderBy产生了一个有序的数据集排序,它在O(n log n)中执行,而这个问题可以通过一次遍历数据集来解决,从而产生O(n)的执行顺序。我建议下载morelinq库(也可以通过NuGet获得),它提供了MinBy扩展来实现这一点。

或者,正如octaviocci已经指出的那样,您可以在O(n)中使用Aggregate。

最新更新