2017-01-12 241 views
0

所以我知道如何計算平均值,但我不知道如何計算最小值和最大值。我很確定你需要使用for循環,但我不知道如何去做。如何從數組列表中獲取最小值和最大值C#

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; 


    } 
} 

我該如何編輯它以便計算最小和最大值?

+5

'INT分鐘= saleslist.Min(); int max = saleslist.Max();' –

+0

@TimSchmelter顯然,OP想要做瘦自我。 – HimBromBeere

+0

@HimBromBeere:顯然OP要麼不知道這些方法,要麼不想使用它們。 –

回答

0
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; 
    } 
} 
+0

我非常愛你。謝謝!有用。 – David

相關問題