2013-12-11 79 views
4

在我的示例类中,它包含的IdValues是int?[]。这些值来自另一个具有Id作为关键字段的类。不能将类型int []隐式转换为int?[]

//Database class 
public class SampleValues // this is a entity that i want to collect the deatil id 
{ 
    public int Id { get; set; } 
    public int?[] SampleDetailIdValue { get; set; } 
} 

public class SampleDetailValues // this is the detail entity 
{ 
    public int Id { get; set; } 
} 


// The error code 
if (sampleDetails.Count > 0) 
{ 
    sample.IdValues = sampleDetails.Select(s => s.Id).ToArray(); // << The error occurred this line. 
} 

的错误是无法隐式转换类型int[]int?[]

回答

4

演员在您的投影:

sample.IdValues = sampleDetails.Select(s => (int?)s.Id).ToArray(); 

你被投射int,呼吁ToArray给你一个int[],所以索性改为投影int?

有交替的Cast扩展方法:

sample.IdValues = sampleDetails 
    .Select(s => s.Id) 
    .Cast<int?>() 
    .ToArray(); 
1

它不能隐式转换,但有明确的转换应该工作

sample.IdValues = sampleDetails.Select(x => x.Id) 
           .Cast<int?>() 
           .ToArray(); 
相关问题