Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法确定条件表达式的类型,因为';int?&x27;和';字符串';_C#_Linq - Fatal编程技术网

C# 无法确定条件表达式的类型,因为';int?&x27;和';字符串';

C# 无法确定条件表达式的类型,因为';int?&x27;和';字符串';,c#,linq,C#,Linq,我有一行代码: Ages = m.RelatedMultipleWorks.Count == 0 ? m.RelatedLook.Age: m.RelatedLook.Age.ToString() + " | " + m.RelatedMultipleWorks. Select(z => z.RelatedLook.Age.ToString()).

我有一行代码:

Ages = m.RelatedMultipleWorks.Count == 0 ? 
       m.RelatedLook.Age: m.RelatedLook.Age.ToString() + " | " +
                          m.RelatedMultipleWorks.
                            Select(z => z.RelatedLook.Age.ToString()).
                            Aggregate((current, next) => current + " | " + next)
整行代码给出了以下错误:

Type of conditional expression cannot be determined because there is no implicit conversion between 'int?' and 'string' 

我不明白为什么我会犯这个错误。我怎样才能摆脱它?谢谢。

您的
m.RelatedLook.Age
可能是一个
int?
,但是由于
.Aggregate
的缘故,二次三元表达式的结果是一个
字符串

Ages
(大概)期望
int?
;三元数的后半部分不能隐式转换为
int?
,因此编译器会对您大喊大叫。这是假设
.Ages
int?
,否则您应该
.ToString()
检查
m.RelatedLook.Age
的结果

<存储>代码> >年龄>代码>听起来有点难闻,但是-考虑-也许使用<代码> iQueDebug < /代码>代替?


我最初试图解释这个答案,可能是因为
Ages
类型不正确,但我应该解释,这是因为三元数不能同时解析为string和int?因为这些类型是不等价的。只需
ToString
ing第一个年龄段就可以修复编译器错误。

三元运算符希望两个输出的类型相同。使用以下命令:

Ages = m.RelatedMultipleWorks.Count == 0 ? m.RelatedLook.Age.ToString(): m.RelatedLook.Age.ToString() + " | " + m.RelatedMultipleWorks.Select(z => z.RelatedLook.Age.ToString()).Aggregate((current, next) => current + " | " + next),

只需在第一个
m.RelatedLook.Age
之后添加一个
ToString
。您希望
Ages
是什么类型
m.RelatedLook.Age
是一个
int?
m.RelatedLook.Age.ToString()…
是一个
字符串
。在表达式的同一部分中,您曾经根据条件分配
int
字符串
,这是不可能的。您可以将
.TosTring()
添加到第一个年龄段,也可以将其从第二个年龄段删除。取决于
年龄的类型。实际上问题在于条件运算符的两个部分不匹配,并且没有共同的隐式转换。一旦这一问题得到解决,可能还会出现转换为任何类型的问题,但这不是错误消息的意思。这是我的意思,但我没有很好地解释它。我会把它加进去;谢谢。是的,我想将
age
存储为字符串,为什么我需要
IEnumerable
?谢谢。如果你愿意的话,你可以将它存储为字符串,但是我觉得,如果你想将一个整数列表存储为一个管道分隔的字符串,我会感到有些“不舒服”。