在数字生成器中显示偶数的数量?

时间:2017-02-23 01:33:02

标签: c#

如何添加显示此处生成的偶数的代码,而不是显示生成的所有偶数,以及在哪里添加?

class Program
    {
        static void Main(string[] args)
        {
            Random number = new Random();
            int rangeFrom = 1;
            int rangeTo = 999;
            List<int> generatedNumbers = new List<int>();

            for (int counter = 0; counter < 100; counter++)
            {
                generatedNumbers.Add(number.Next(rangeFrom, rangeTo));
            }

            generatedNumbers.Sort();

            string output = "Numbers: {0} \r\n\rMinimum Number: {1}\r\n\r\nMaximum Number: {2}\r\n\r\nRange of Numbers: {3}-{4}";

            output = string.Format(output, string.Join(", ", generatedNumbers.ToArray()), generatedNumbers.Min(), generatedNumbers.Max(), rangeFrom, rangeTo);


            MessageBox.Show(output);
        }
    }
}

3 个答案:

答案 0 :(得分:3)

尝试这样generatedNumbers.Where(x => x % 2 == 0).Count()

string output = "Numbers: {0} \r\n\r\nEven Numbers: {1} \r\n\r\nMinimum Number: {2}\r\n\r\nMaximum Number: {3}\r\n\r\nRange of Numbers: {4}-{5}";

output = string.Format(output, string.Join(", ", generatedNumbers.ToArray()), generatedNumbers.Where(x => x % 2 == 0).Count(), generatedNumbers.Min(), generatedNumbers.Max(), rangeFrom, rangeTo);

为了让您的代码更具可读性,您也可以这样做:

Random number = new Random();

int rangeFrom = 1;
int rangeTo = 999;

List<int> generatedNumbers =
    Enumerable
        .Range(0, 100)
        .Select(x => number.Next(rangeFrom, rangeTo + 1))
        .OrderBy(x => x)
        .ToList();

var results = new []
{
    "Numbers: " + String.Join(", ", generatedNumbers),
    "Even Numbers: " + generatedNumbers.Where(x => x % 2 == 0).Count(),
    "Minimum Number: " + generatedNumbers.Min(),
    "Maximum Number: " + generatedNumbers.Max(),
    "Range of Numbers: " + rangeFrom + "-" + rangeTo,
};

string output = String.Join(Environment.NewLine + Environment.NewLine, results);

MessageBox.Show(output);

答案 1 :(得分:1)

对于更有文化的编程,您可以定义谓词函数:

Func<Int32,Boolean> isEven = i => i % 2 == 0;

var count = generatedNumbers.Count(isEven);

答案 2 :(得分:0)

var evenNumbers = generatedNumbers.Where(n => (n % 2) == 0)

然后您只需将evenNumbers.Count()添加到输出字符串