【问题标题】:Cannot convert 'System.Collections.Generic.List<long?>' to 'System.Collections.Generic.List<long>无法将 'System.Collections.Generic.List<long?>' 转换为 'System.Collections.Generic.List<long>
【发布时间】:2016-07-30 19:45:41
【问题描述】:

使用ObservableCollection 和LINQ 查询从SQL Server 数据库表中获取int,我遇到了这个错误。应该返回一个 4 位整数,像这样3125

CS1503 参数 1:无法从 'System.Collections.Generic.List' 到 'System.Collections.Generic.List'

这怎么可能?它与List 中的类型相同。

我的代码,

public static ObservableCollection<long> SearchNameComboStaffNo(DatabaseDataContext database, string staffNameFirst, string staffNameSecond)
        {
            return new ObservableCollection<long>
                   (database.Staff_Data_TBLs
                    .Where(staff => staff.Staff_Name_First == staffNameFirst &&                             
                     staff.Staff_Name_Second == staffNameSecond)
                    .Select(staff => staff.Staff_No).ToList());
        }

无论我尝试什么,我总是得到一个编译错误。但是,同类型怎么不能转换呢?

【问题讨论】:

  • long?long 的类型不同。 long? 可能处于无效状态,因此不能直接转换为 long
  • @nshct,啊,我明白了。那么这将如何修改才能起作用呢?我不能,不管我做什么。
  • 要么将您的返回类型更改为ObservableCollection&lt;long?&gt;,要么实现Grant Winney's answer

标签: c# linq


【解决方案1】:

很可能,staff.Staff_No 不是表中的必需列,因此它返回一个可为空的 long 而不是 long

如果您想将其存储在long 的列表中,请修改您的查询以为其提供默认值。

return new ObservableCollection<long>
       (database.Staff_Data_TBLs
                .Where(staff => staff.Staff_Name_First == staffNameFirst &&                             
                       staff.Staff_Name_Second == staffNameSecond)
                .Select(staff => staff.Staff_No ?? 0).ToList());

如果它是数据库中的int,并且您需要将其存储在long 的集合中,则需要先对其进行转换,否则您将收到类似"无法转换的错误从 List 到 List"

.Select(staff => (long)staff.Staff_No ?? 0).ToList());

【讨论】:

  • 只是好奇,数据库中的类型是int。我需要返回int 还是足够长的?
  • 格兰特,如果我能最后一次打扰你,为什么 LINQ 将staff_No 归类为long,而它在数据库中是int?这只是为了我的理解。
  • 好的,我想我现在明白了。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2011-07-06
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多