2017-10-04 6 views
1

リストと配列を文の途中で1行に出力しようとしていますが、各要素をカンマで区切ります。 たとえば、22.3、44.5、88.1を含むdblListの場合、「リスト(22.3、44.5、88.1)の場合、その要素の平均は平均です」というような出力が必要です。リスト/配列を1行に書く

私はそれが本当に簡単だと確信していますが、私はそれを理解することはできません。

助けが必要ですか?

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace Averages 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<int> integerList1 = new List<int> { 3 }; 
      List<int> integerList2 = new List<int> { 12, 15 }; 
      List<double> dblList = new List<double> { 22.3, 44.5, 88.1 }; 
      int[] myArr = { 3, 4, 5, 6, 7, 8 }; 
      CalculateAverage(integerList1, integerList2, dblList, myArr); 
     } 

     private static void CalculateAverage(List<int> intlist1, List<int> intlist2, List<double> dblist, int[] myArr) 
     { 
      Console.WriteLine($"For the list ({intlist1}), the average of its elements is: {intlist1.Average():F}"); 
      Console.WriteLine($"For the list ({intlist2}), the average of its elements is: {intlist2.Average():F}"); 
      Console.WriteLine($"For the list ({dblist}), the average of its elements is: {dblist.Average():F}"); 
      Console.WriteLine($"For the array [{myArr}], the average of its elements is: {myArr.Average():F}"); 
      Console.ReadLine(); 
     } 
    } 
} 

+2

[区切りの文字列にC#の一覧]の可能な重複(https://stackoverflow.com/questions/3575029/c-sharp-リストストリングとストリング付き区切り文字) – zerkms

+0

string output = string.Format( "({0})"、string.Join( "、"、dblList.Select(x => x.ToString()))); – jdweng

答えて

1

使用string.Join

List<double> dblList = new List<double> { 22.3, 44.5, 88.1 }; 

Console.WriteLine(string.Format("Here's the list: ({0}).", string.Join(", ", dblList))); 

// Output: Here's the list: (22.3, 44.5, 88.1). 
関連する問題