在C#中从数组中查找最小值和最大值

时间:2018-12-09 22:58:43

标签: c# arrays

我正在一个项目中,该项目涉及使用数组将数据从CSV文件导入到C#程序中,并返回最小值和最大值之类的值。我一直难以实现返回最大值和最小值的方法。

样品课:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Thomas_Nicholas_E2
{
    class Samples
    {
        public double Fenner { get; set; }
        public double Abom { get; set; }

        public Samples()
        {

        }

        public void ReadCsv(StreamReader reader)
        {
            string buffer;
            string[] parts;

            // Get record from file
            buffer = reader.ReadLine();

            // Break record into components
            parts = buffer.Split(',');

           /* Array.Sort<string>(parts);
            foreach (var x in parts)
            {
                Console.WriteLine(x);
            }
            */
            // Convert field values to variable
            Fenner = Convert.ToDouble(parts[0]);
            Abom = Convert.ToDouble(parts[1]);


            // Finding the range of the datasets 
            //var sortedFenner = parts[0].OrderBy(i => i);
            //var sortedAbom = parts[1].OrderBy(i => i);
            //var sortedTotal = parts.OrderBy(i => i);
            //Console.WriteLine(sortedAbom);
            //Console.WriteLine(parts.Max());
            //double minimum1 = Math.Min(parts, parts);
            //Console.WriteLine(parts[1].Min());

            //string min = parts[0].Min();
            // Console.WriteLine(min);
            //double min = parts[1].Min();
            //Console.WriteLine(min);
        }

    }
}

您可以在Samples类底部的注释掉的部分中看到到目前为止我已经尝试过的内容。

程序类以防万一:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Thomas_Nicholas_E2
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader("examdata.csv");

            string buffer;

            double totalFenner = 0.0;
            double totalAbom = 0.0;
            double total = 0.0;
            double minumum = 0.0;
            double maximum = 0.0;
            double range = 0.0;
            double meanFenner = 0.0;
            double meanAbom = 0.0;
            double meanTotal = 0.0;

            // Read header to get it out of the way
            buffer = reader.ReadLine();

            while(!reader.EndOfStream)
            {
                Samples MySamples = new Samples();
                MySamples.ReadCsv(reader);

                // Processing
                //Calculating totals
                totalFenner += MySamples.Fenner;
                totalAbom += MySamples.Abom;
                total = (totalFenner + totalAbom);

                //Calculating means
                meanFenner = (totalFenner / 20);
                meanAbom = (totalAbom / 20);
                meanTotal = (total / 40);


                // += MySamples;

                //Console.WriteLine("TransId: {0}  DeptNo: {1}  Amt: {2}", transId, deptNo, amt);
                //MyTransaction.Print();
            }
            Console.WriteLine(meanFenner);
            Console.WriteLine(meanAbom);
            Console.WriteLine(meanTotal);
            //Console.WriteLine(Samples.sortedAbom)




            reader.Close();

            Pause();
        }
        private static void Pause()
        {
            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

感谢您的任何建议或指导,谢谢。

3 个答案:

答案 0 :(得分:1)

使用重载的Factory pattern方法在ReadCsv()类中构建Samples方法,如下所示:

public static Samples ReadCsv(StreamReader reader)
{
    return ReadCSv(reader.ReadLine());
}

public static Samples ReadCsv(string line)
{
    parts = line.Split(',');
    return new Samples() {
        Fenner = Convert.ToDouble(parts[0]),
        Abom = Convert.ToDouble(parts[1])
    };
}

然后您可以通过Main()方法使用它,如下所示:

static void Main(string[] args)
{
    var samples = File.ReadLines("examdata.csv")
                 .Select(l => Samples.ReadCsv(l))
                 .ToList();

    double totalFenner = samples.Select(s => s.Fenner).Sum();
    double totalAbom = samples.Select(s => s.Abom).Sum();
    double total = totalFenner + totalAbom;

    double meanFenner = sampes.Select(s => s.Fenner).Avg();
    double meanAbom = samples.Select(s => s.Abom).Avg();
    double meanTotal = samples.Select(s => s.Fenner + s.Abom).Avg();

    Console.WriteLine(meanFenner);
    Console.WriteLine(meanAbom);
    Console.WriteLine(meanTotal);

     Pause();
}

或类似的代码(更多代码,但是运行起来更快,更容易理解):

static void Main(string[] args)
{
    double totalFenner = 0.0;
    double totalAbom = 0.0;
    double total = 0.0;

    double meanFenner = 0.0;
    double meanAbom = 0.0;
    double meanTotal = 0.0;

    var samples = File.ReadLines("examdata.csv")
                 .Select(l => Samples.ReadCsv(l));

    int count = 0;
    foreach (var sample in samples)
    {
        totalFenner += sample.Fenner;
        totalAbom += sample.Abom;
        count++;
    }
    total = totalFenner + totalAbom;
    meanTotal = total / count;
    meanFenner = totalFenner / count;
    meanAbom = totalAbom / count;

    Console.WriteLine(meanFenner);
    Console.WriteLine(meanAbom);
    Console.WriteLine(meanTotal);

     Pause();
}

答案 1 :(得分:0)

查找最小值/最大值非常容易。假设数组或列表,您可以简单地在其上调用.Min().Max()。例如:

var foo = new List<int> {4,3,5,9,1};
var min = foo.Min();
var max = foo.Max();

答案 2 :(得分:0)

我认为为评论中看到的一些答案提供一些代码可能会有用。

要阅读所有行,您可以执行以下操作:

    using (StreamReader reader = new StreamReader("examdata.csv")) {

      while ((buffer = reader.ReadLine()) != null)
      {
         // Something
      }

    }

然后,如果您使用的是数组,则可以执行@gilliduck所说的操作,并使用.Min().Max()查找最小/最大值。