【问题标题】:How to get minimum and maximum value from array list C# [duplicate]如何从数组列表C#中获取最小值和最大值[重复]
【发布时间】:2017-01-12 12:32:10
【问题描述】:

所以我知道如何计算平均值,但我不知道如何计算最小值和最大值。我很确定您需要使用 for 循环,但我不知道该怎么做。

 public Int32 Average
{
    get
    {
        clsSimpleDataConnection Datalayer = new clsSimpleDataConnection();
        List<Int32> saleslist = new List<Int32>();
        saleslist = Datalayer.LoadIntegerList();
        Int32 AnItem;
        Int32 Total = 0;
        Int32 average;
        Int32 itemcount;
        itemcount = saleslist.Count;
        Int32 index = 0;

        while (index < itemcount)
        {
            AnItem = saleslist[index];
            Total = Total + AnItem;
            index++;

        }
            average = Total / itemcount;
        return average;


    }
}

我将如何编辑它以计算最小值和最大值?

【问题讨论】:

  • int min = saleslist.Min(); int max = saleslist.Max();
  • @TimSchmelter 显然 OP 想做瘦身。
  • @HimBromBeere:显然 OP 要么不知道这些方法,要么不想使用它们。
  • @大卫。显示到目前为止您所做的以找到最小值或最大值。我们在这里不仅仅是为您编写代码。做点什么,也许我们可以帮助解决您遇到的任何小错误
  • 你从“身份元素”或“中性元素”开始:en.wikipedia.org/wiki/Identity_element

标签: c#


【解决方案1】:
var myList = new List<int>();
var min = myList.Min();
var max = myList.Max();

或者如果你想使用循环 所以对于最大值

int max = int.MinValue;
foreach (var type in myList)
{
    if (type > max)
    {
        max = type;
    }
}

为分钟

int min = int.MaxValue;
foreach (var type in myList)
{
    if (type < min)
    {
        min= type;
    }
}

【讨论】:

  • 我非常爱你。谢谢!它有效。
猜你喜欢
  • 1970-01-01
  • 2019-09-19
  • 2017-05-24
  • 2010-11-23
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多