【问题标题】:Write list/array on a single line在一行上写入列表/数组
【发布时间】:2018-03-15 07:23:46
【问题描述】:

我试图在句子中间输出我的列表和数组,用逗号分隔每个元素。 例如,包含 22.3、44.5、88.1 的 dblList 我需要输出如下所示,“对于列表 (22.3, 44.5, 88.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();
        }
    }
}

【问题讨论】:

标签: c# arrays list


【解决方案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).

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 2014-01-28
    • 2019-04-09
    • 1970-01-01
    • 2014-02-23
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多