Add/Insert 双 AND 字符串到列表

Add/Insert double AND string into a list

所以,很快。是否可以在列表中插入双精度和字符串?像这样:

 if (input2 == 0)  // this boolean checks if the first number is devided by zero, then:
                {
                    listOfResults.Insert(index: temp, item: "You divided by 0! Wait, thats illegal"); // and thats what i want, to add a string into the position of the list when the input is 0
                }
                else
                {
                    result = (double)input1 / (double)input2; // the input numbers are int but i cast them to double 
                    listOfResults.Insert(index: position, item: result);
                }

我的输入是:3 和 2、6 和 3、-4 和 0、1 和 2,我将每个第一个数字除以第二个输入数字。
输出应该是这样的:

1.5
2
你除以0!等等,那是非法的
0.5
那么是否可以为列表中的每个位置存储双精度和字符串?

列表将允许这两种类型。您可以使用 typeof() == typeof(double),例如,在使用值时,或者只是使用 ToString()。

static void Main(string[] args)
{
   List<object> myData = new List<object>()
   {
                1.234,
                -0.1,
                "divide by zero",
                100.0
   };

   foreach (object item in myData)
   {
      Console.WriteLine(item.ToString());
   }
}

是的,您可以创建一个 List,它可以包含任何数据类型,double、string、int、其他对象等。

更好的选择可能是定义一个 Result 对象,例如

class Result
{
    public bool Error { get; set; } = false;
    public double Value { get; set; }
    public string ErrorMessage { get; set; } = "";
}

然后存储一个List的列表,这样你就不需要转换或检查类型了。

您可以使用元组列表:

var tupleList = new List<(double, string)>();
tupleList.Add((2.5, "a string"));

根据您的代码,我将执行以下操作:

var listOfResults = new List<(double? result, string error)>();
if (input2 == 0)
{
    listOfResults.Insert(index: temp, item: (null, "You divided by 0! Wait, thats illegal"));
}
else
{
    result = (double)input1 / input2;
    listOfResults.Insert(index: position, item: (result, null));
}

打印输出的方法如下:

foreach (var item in listOfResults)
{
    if (item.result.HasValue)
        Console.WriteLine(item.result);
    else
        Console.WriteLine(item.error);
}