6

I'm trying to output my lists and arrays in the middle of the sentence all in one line with commas separating each element. For example, dblList which contains 22.3, 44.5, 88.1 I need the output to look like this, "For the list (22.3, 44.5, 88.1), the average of its elements is: average."

I'm sure it's really easy to do but I can't figure it out.

Any help?

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();
        }
    }
}

Pang
  • 9,564
  • 146
  • 81
  • 122
Seanut Brittle
  • 63
  • 1
  • 1
  • 3
  • 3
    Possible duplicate of [C# List to string with delimiter](https://stackoverflow.com/questions/3575029/c-sharp-liststring-to-string-with-delimiter) – zerkms Oct 04 '17 at 01:36
  • string output = string.Format("({0})", string.Join(",",dblList.Select(x => x.ToString()))); – jdweng Oct 04 '17 at 01:47

1 Answers1

20

Use 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).
user94559
  • 59,196
  • 6
  • 103
  • 103