在 LINQ 中使用 select new 返回列表 [英] Return list using select new in LINQ

查看:61
本文介绍了在 LINQ 中使用 select new 返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的方法,它给了我错误.

This is my method which gives me error.

public List<Project> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                    select new { pro.ProjectName, pro.ProjectId };

        return query.ToList();
    }
}

如果我用这个来改变它:

If i change it with this:

public List<Project> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                    select pro;

        return query.ToList();
    }
}

然后它工作正常,没有错误.

Then it works fine with no errors.

你能告诉我如何只返回 ProjectIdProjectNam 吗?

Can you please let me know that how I can return only ProjectId and ProjectNam?

推荐答案

方法不能返回匿名类型.它必须与方法返回类型中定义的类型相同.检查 GetProjectForCombo 的签名并查看您指定的返回类型.

Method can not return anonymous type. It has to be same as the type defined in method return type. Check the signature of GetProjectForCombo and see what return type you have specified.

创建一个具有所需属性的类 ProjectInfo,然后在新的表达式中创建 ProjectInfo 类型的对象.

Create a class ProjectInfo with required properties and then in new expression create object of ProjectInfo type.

class ProjectInfo
{
   public string Name {get; set; }
   public long Id {get; set; }
}

public List<ProjectInfo> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                    select new ProjectInfo(){ Name = pro.ProjectName, Id = pro.ProjectId };

        return query.ToList();
    }
}

这篇关于在 LINQ 中使用 select new 返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆