c# - 如何分离 double 和字符串项,出现无效的转换错误

标签 c# double boxing

我有一个Dictionary<string, object>其中有stringdouble值为 object 。现在我想在下面的代码中分离这两种值类型。目前我收到无效转换错误。如何做到这一点?

namespace ConsoleApp26
{
public class Sample
{
    public string SampleName;
    public Dictionary<string, object> SampleValues;
}

public class SampleDivideBetweenDoubleAndStringValue
{
    public string Name { get; set; }
    public double DoubleValue { get; set; }
    public string StringValue { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var samples = new Sample
            {
                SampleName = "test",
                SampleValues = new Dictionary<string, object> { 
                    { "t1",  45.08 }, 
                    { "t2", "A String Value" }, 
                    { "t3",  83 } 
                }
            };

            var tuple = GetTuple(samples);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        Console.ReadKey();
    }

    private static Tuple<IEnumerable<SampleDivideBetweenDoubleAndStringValue>, IEnumerable<SampleDivideBetweenDoubleAndStringValue>> GetTuple(Sample samples)
    {
        var doubles = (from s in samples.SampleValues
                       select new SampleDivideBetweenDoubleAndStringValue
                       {
                           Name = samples.SampleName,
                           DoubleValue = (double)s.Value
                       });

        var strings = (from s in samples.SampleValues
                       select new SampleDivideBetweenDoubleAndStringValue
                       {
                           Name = samples.SampleName,
                           StringValue = (string)s.Value
                       });

        return new Tuple<
          IEnumerable<SampleDivideBetweenDoubleAndStringValue>, 
          IEnumerable<SampleDivideBetweenDoubleAndStringValue>>(doubles, strings);
    }
}
}

最佳答案

数据结构的主要问题是,不仅有 stringdouble,还有 int:

  var SampleValues = new Dictionary<string, object> { 
    { "t1",  45.08 },             // boxed double value
    { "t2", "A String Value" },   // string value
    { "t3",  83 },                // <- N.B. this is boxed int (83), not double (83.0) value
  };

将装箱的 int 转换为 double 抛出异常:

  object o = 83;         // int value (83) which is boxed into object

  double d = (double) o; // <- Exception will be thrown here (invalid cast)

请注意,转换是可以的:

  object o = 83;

  double d = Convert.ToDouble(o); // d == 83.0

因此,您可以尝试过滤掉 String 项目,然后转换所有其余内容(doubleint 值)转换为 double;在你的情况下:

  var doubles = samples
    .SampleValues       
    .Where(pair => (pair.Value != null) && !(pair.Value is string)) // not string value
    .Select(pair => new {
       Name  = samples.Name,
       Value = Convert.ToDouble(pair.Value), // which we convert to double
     });

  var strings = samples
    .SampleValues       
    .Where(pair => pair.Value is string)
    .Select(pair => new {
       Name  = samples.Name,
       Value = Convert.ToString(pair.Value),
     });

关于c# - 如何分离 double 和字符串项,出现无效的转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59947629/

相关文章:

c - malloc() 和固定大小的简单声明之间的区别

java - 在条件表达式中混合 Integer 和 Double

c# - 从对象盒类型进行通用转换

c# - 'List' 不包含 'Where' 的定义

c# - 如何在VS2010中打开.ccproj?

c# - 如何在 html 按钮单击时连接服务器端编程 (c#)

c# - 如何在 C# 中使用正则表达式匹配字符串

css - 双 CSS 属性,否则该属性将不起作用

java - 我把double转成了int,但是还是报错,解释一下为什么?

vb.net - VB.NET“如果”运算符会导致装箱吗?