我有一个Dictionary<string, object>
其中有string
和double
值为 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);
}
}
}
最佳答案
数据结构的主要问题是,不仅有 string
和 double
,还有 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
项目,然后转换
所有其余内容(double
和 int
值)转换为 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/