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

时间:2015-12-31 23:25:59

标签: linq c#-4.0

我的程序在下面给出了字符串数组中最短的国家字符数。如何使用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);
    }
}

3 个答案:

答案 0 :(得分:3)

一种简单的方法是按名称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);

答案 1 :(得分:2)

按名称长度排序所有国家/地区,然后选择第一个(最短)和最后一个(最长):

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

答案 2 :(得分:1)

我知道这个问题已经有了一个已经接受的答案,这个答案对于给出的具体例子来说是完全足够的,但是读到这个的任何人都应该记住它不能像它应该的那样扩展。 OrderBy导致在O(n log n)中执行的有序排序的数据集,而问题可以通过数据集的单次传递来解决,从而导致执行顺序为O(n)。我建议下载morelinq库(也可以通过NuGet获取),该库提供MinBy扩展名来完成此操作。

或者你也可以在O(n)中使用Aggregate,就像octaviocci已经指出的那样。