有人能告诉我我的类型或linq查询有什么问题吗?

本文关键字:查询 什么 问题 linq 告诉我 我的 类型 | 更新日期: 2023-09-27 18:12:28

我希望有人能帮助我,我的错误是

不能隐式地将system.collections.generic.List类型转换为xxxlistlitems

我有这个

public IDListItems getIDList()
{
    IDListItems items = new IDListItem();
    try
    {
        var x = (from c in db.ap_GetIDListItems()
               select new IDListItems { CId = c.CID, Id = c.ID }).ToList();
        items = x;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return items;   
}

然后我有一个像这样的类

namespace SaSs
{
    public class IDListItems 
    {
        public int Id {get; set;}
        public string CId { get; set; }
    }
}

我认为这是一个问题与我的返回类型,但我不确定如何为类型返回列表

有人能告诉我我的类型或linq查询有什么问题吗?

呃…因为项目不是一个列表?

List<IDListItems> items = new List<IDListItem>();

其他人建议更改变量的类型—我建议完全删除变量,以及无意义的catch块。您还需要更改返回类型:

public List<IDListItems> getIDList()
{
    return (from c in db.ap_GetIDListItems()
            select new IDListItems { CId = c.CID, Id = c.ID }).ToList();
}

或者没有无意义的查询表达式:

public List<IDListItems> getIDList()
{
    return db.ap_GetIDListItems()
             .Select(c => new IDListItems { CId = c.CID, Id = c.ID })
             .ToList();
}

项为IDListItems。不能将IDListItems分配给List<IDListItems>

您需要将其设置为如下的列表

List<IDListItems> items = new List<IDListItem>();

这样应该可以

public List<IDListItems> GetIDList()
        {
            List<IDListItems> items = new List<IDListItems>();
        try
        {
            var x = (from c in db.ap_GetIDListItems()
                     select new IDListItems { CId = c.CID, Id = c.ID }).ToList();
            items = x;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return items;   
    }

如果您调用GetIDList(),您也需要更改这一点。您还需要在此语句中添加一个适当的catch语句。

try:

public List<IDListItems> getIDList()
{
    List<IDListItems> items = new List<IDListItems>();
    try
    {
        var x = (from c in db.ap_GetIDListItems()
                 select new IDListItems { CId = c.CID, Id = c.ID }).ToList();
        items = x;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return items;   
}