1

我正在尝试使用以下表达式为下拉列表进行 LINQ 选择:

    protected void PopulateInstitutionsDropDownList(Team currentTeam)
    {
        var institutions = from d in db.Institutions
                           where !(currentTeam.Institutions.Select(x => x.ID).Contains(d.ID))
                           orderby d.InstitutionName
                           select d;

        List<Institution> i = institutions.ToList();

        ViewBag.Institutions = new SelectList(i, "ID", "InstitutionName");
    }

但是,这会导致异常:无法创建类型为“Refusion.Models.Institution”的常量值。此类型仅支持原始类型或枚举。

这就是为什么我尝试只选择新集合的 ID,因为我知道如果没有 Compare 对象,它无法直接比较两个对象。

为什么这不起作用?

4

3 回答 3

4

这样的事情呢?你考虑过Except吗?

IEnumerable<Institutions> institutions = db.Institutions.Except(currentTeam.Institutions);
于 2013-05-10T18:35:16.967 回答
3

我认为你的sintax可能是错的。过去我用它来阻止用户显示:

string[] blockedUsers = { "Jair","Jean" };


Users.Where (c => !blockedUsers.Contains (c.Name))
    //"This translates to SQL WHERE NOT ... IN"

希望能帮助到你。

编辑1:

public class Institution
{
    public int id { get; set; }
    public string name { get; set; }
}

public class Team
{
    public int id { get; set; }
    public string name { get; set; }
    public int InstId { get; set; }
}


protected void Page_Load(object sender, EventArgs e)
{

    Team currentTeam = new Team() { id = 1, InstId = 2, name = "Team 1 in Institute 2" };

    Institution inst1 = new Institution() { id = 1, name = "Inst1" };
    Institution inst2 = new Institution() { id = 2, name = "Inst2" };
    Institution inst3 = new Institution() { id = 3, name = "Inst3" };

    List<Institution> institutions = new List<Institution>();

    institutions.Add(inst1); institutions.Add(inst2); institutions.Add(inst3);

    var allowedInst = institutions.Where(i => !(i.id == currentTeam.InstId));


    foreach (Institution inst in allowedInst)
    {
        //it should show institutes 1 and 3
        Response.Write(inst.id + " - " + inst.name + "<br/>");
    }
}
于 2013-05-10T21:31:45.690 回答
1

问题是你在哪里。请执行下列操作

List<int> IDs = currentTeam.Institution.Select(x=>x.ID).ToList()

那么你的 where 应该是这样的

where !(IDs.Any(x => x==d.ID)
于 2013-05-10T18:15:58.817 回答