C# 搜索表单有一个枚举下拉字段,一旦到达我的lambda Linq查询,其值可能为null(未选择)

C# 搜索表单有一个枚举下拉字段,一旦到达我的lambda Linq查询,其值可能为null(未选择),c#,asp.net-mvc,linq,lambda,enums,C#,Asp.net Mvc,Linq,Lambda,Enums,基本上,如果用户从下拉组合中选择了no选项,我希望它不会出现在我的Linq查询中,如下所示: // this is how I manage the form post data, please // propose a better way if you know one Dictionary<string, string> formdata = new Dictionary<string, string>(); foreach(string key in Requ

基本上,如果用户从下拉组合中选择了no选项,我希望它不会出现在我的Linq查询中,如下所示:

// this is how I manage the form post data, please 
// propose a better way if you know one
Dictionary<string, string> formdata = new Dictionary<string, string>();

foreach(string key in Request.Form.AllKeys)
{
    formdata.Add(key, Request.Form[key]);
}    

// getting the title
string title = "";
formdata.TryGetValue("postedTitle", out title);

// getting the level
string levelString = "";
formdata.TryGetValue("postedLevel", out levelString );

int level = -1;
if(levelString != "")
{
    Int32.TryParse(levelString , out level);
}


var model = new FooIndexVM
{
    Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....
由于级别为0或-1,因此我需要一种方法将枚举部分完全从查询中删除。稍后我还会添加一些类似于此字段的附加字段,这些字段可能会被取消选中,因此解决方案也适用于这些字段。

您可以将命令链接到何处,以便此行:

Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....
在不改变其行为的情况下,可以将多个有效地与&&s结合起来:

这意味着您可以添加一些关于是否应用第二个的逻辑,例如:

var query = _ctx.SomeDbSet.Where(w => w.Title.Contains(title));
if (level != -1)
{
  query = query.Where(w => w.Level == (Level?)level.Value)
}

Foos = query.Select(x => new FooBarRow
            {
                FooBarId = x.Id,
可以将命令链接到何处,以便此行:

Foos = _ctx.SomeDbSet.Where(w => w.Title.Contains(title) && w.Level == (Level?)level.Value).Select(x => new FooBarRow
            {
                FooBarId = x.Id,
                ....
在不改变其行为的情况下,可以将多个有效地与&&s结合起来:

这意味着您可以添加一些关于是否应用第二个的逻辑,例如:

var query = _ctx.SomeDbSet.Where(w => w.Title.Contains(title));
if (level != -1)
{
  query = query.Where(w => w.Level == (Level?)level.Value)
}

Foos = query.Select(x => new FooBarRow
            {
                FooBarId = x.Id,

太好了,它起作用了。我不知道where子句是可链接的。非常感谢!太好了,它起作用了。我不知道where子句是可链接的。非常感谢!