【问题标题】:C#: Error-Cannot implicitly convert type 'int' to 'System.Collections.Generic.IEnumerable<double>'C#:错误 - 无法将类型“int”隐式转换为“System.Collections.Generic.IEnumerable<double>”
【发布时间】:2017-02-27 08:38:20
【问题描述】:

我试图覆盖一个对象EducationData的中值,模型定义如下,

// EducationData model
[DataMember(Name = "DegreeConferred", Order = 1)]
public int DegreeConferred { get; set; }
[DataMember(Name = "NoOfInstitutions", Order = 3)]
public int NoOfInstitutions { get; set; }
[DataMember(Name = "Mean", Order = 6)]
public int Mean { get; set; }
[DataMember(Name = "Median", Order = 7)]
public IEnumerable<double> Median { get; set; }

CachedData为var类型,包含教育详情的ES查询结果如附图。

我必须通过一些更改来覆盖该中值。我试过的代码段如下。

var resultData = cachedData.ToArray();
resultData[0].Mean = resultData[0].DegreeConferred / resultData[0].NoOfInstitutions; // calculated mean with no error
var updatedMedian = 7; // say for sample, because there is a need to override this queried value with some modification.
resultData[0].Median = updatedMedian; // Error line: Cannot implicitly convert type 'int' to 'System.Collections.Generic.IEnumerable<double>'

请注意:在模型中将属性更改为 int 会影响其他地方的实现。所以在这里做铸造会更好。

我尝试了 ReSharper 建议,但没有任何效果

resultData[0].Median = Convert.ToDouble(updatedMedian);
resultData[0].Median = IEnumerable<double>updatedMedian;
Also changing the property of updatedMedian will affect the calculation steps.

我也尝试过SO as的一些建议,

  1. LINQ: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'
  2. Linq Query : Cannot convert type IEnumerable<string> to string changing .ToString() to (string)
  3. Cannot implicitly convert type 'System.Collections.Generic.IEnumerable

在过去的一天半里,我一直在为此苦苦挣扎。任何建议都会非常有帮助。

【问题讨论】:

  • 中位数不是int,而是IEnumerable&lt;double&gt;。您不能将元素添加到 IEnumerable。将其更改为List&lt;double&gt; 并使用resultData[0].Median.Add(7.0)
  • Median 似乎是一个双精度数组,将其设置为 int 不起作用。

标签: c# c++ .net generics casting


【解决方案1】:

这会有所帮助!

        resultData[0].Median = new List<double>() {updatedMedian};

【讨论】:

    【解决方案2】:

    没有类型var,并且Median 不是int,而是一个可枚举的double。这意味着它(可能)包含多个值,而不仅仅是一个。

    如果要将Median替换为单个值7,可以创建一个数组:

    resultData[0].Median = new [] { 7d };
    

    【讨论】:

    • 令人印象深刻!谢谢。但是如果我需要传递一个变量说 num 而不是 7 单个常量值。会是什么情况?
    • @MJSuriya 同样,new [] { num }。当然,这是假设 num 是双精度 - 否则您需要将其转换为双精度或显式创建双精度数组 (new double[])。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2020-05-03
    • 1970-01-01
    相关资源
    最近更新 更多