在linq搜索中过滤出空值 [英] Filtering out null values in a linq search

查看:501
本文介绍了在linq搜索中过滤出空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个处理图书和期刊的图书库. 我有一个winform,用户可以在其中输入一些参数以在库DB上进行搜索.我不知道他选择插入哪个值.

Im building a book library which handles Books and Journals. I have a winform where the user enters some parameters to search on the library DB. i do not know which value he selects to insert.

例如:

public abstract class Item : IComparer, IEnumerable
{
    public string Name { get; set; }
    public string Publisher { get; set; }
    public double Price { get; set; }
    public double Discount { get; set; }
    public DateTime ReleaseDate { get; set; }
}

这是我的基础课.当用户可以插入以按名称搜索(翻译成书名)时. 用户界面有许多搜索选项,基本上包括了本书所包含的几乎所有字段.

this is my base class. when a user can insert to search by name (which translates into book name). the UI has many options to search by, and basiclly includes almost all of the fields that a book contains.

我需要做的是仅过滤掉用户插入的字段,然后将它们传递给我的DAL,这样他就可以在ENTITY框架映射的数据库上使用LINQ查询来执行搜索.

What i need to do is filter out only the fields that the user inserted, pass them to my DAL so he can perform the search using a LINQ query on ENTITY framework mapped DB.

这是我到目前为止的搜索:

this is my search so far:

public List<Books> SelectBookFromDB(Item itemType)
{
    BookVO book = itemType as BookVO;
    var result = myEntities.Books.Where(x =>
                                        x.Author == book.Author &&
                                        x.Discount == book.Discount &&
                                        x.Name == book.Name &&
                                        x.Publisher == book.Publisher).ToList();              
    return result;
}

问题是,即时通讯正在搜索一些可能为空的值.这样,我的搜索总是空着的:( 我不知道如何进行.希望有帮助.

problem is, im searching for some values that may be null. that way, my searches always come up empty :( i have no clue how to proceed. would love some help.

谢谢!

推荐答案

使用多个步骤即可生成查询:

Use more then one step to generate the query:

var result = myEntities.Books;

if(string.IsNullOrWhiteSpace(book.Author) == false)
{
  result = result.Where(x => x.Author == book.Author);
}

if(string.IsNullOrWhiteSpace(book.Name) == false)
{
  result = result.Where(x => x.Name == book.Name);
}

...And so on.

return result;

这篇关于在linq搜索中过滤出空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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