C#で配列の平均値を取得するサンプル
書式
List<int> リスト名 = new List<int> {xxx }
リスト名.Average()
int?[] 配列名 = new int?[] {xx}
配列名.Average()
使用例
using System; using System.Collections.Generic; using System.Linq; class Arkgame { public static void Main() { //配列cftAの宣言 int[] cftA = new int[] { 5, 6, 7, 8, 9 }; //配列cftBの宣言 int?[] cftB = new int?[] { 11, 22, 33, 44, null, 55 }; //配列intLst List<int> intLst = new List<int> { 9, 11, 23, 12, 22 }; try { double resA = cftA.Average(); double? resB = cftB.Average(); double resC = intLst.Average(); Console.WriteLine("結果1: " + resA.ToString()); Console.WriteLine("結果2: " + resB.ToString()); Console.WriteLine("結果3: " + resC.ToString()); } catch (Exception e) { System.Console.WriteLine(e.ToString()); } Console.ReadKey(); } }
実行結果
結果1: 7 結果2: 33 結果3: 15.4