在一个LINQ查询中组合两个条件

时间:2018-03-15 06:48:27

标签: c# linq

我想知道是否有办法在一个LINQ查询中将两个条件组合在两个不同的列上?

我有一张书桌 - > tbl_books有三列

id - pk

subject_id - fk to tbl_subjects

book_summary - 书籍摘要详情

var book_ids =不同book_ids列表

var subject_ids =不同subject_id的列表

//This will return books for the provided book_ids
var books1 = db.tbl_books.where(b=> book_ids.contains(b.id)).ToList();

//This will return books for the provided subject_ids
var books2 = db.tbl_books.where(b=>subject_ids.contains(b.subject_id)).ToList();

有没有办法将两个查询合并到一个查询中?

我知道我可以这样做:

db.tbl_books.where(b=> book_ids.contains(b.id)).Union(db.tbl_books.where(b=>subject_ids.contains(b.subject_id))).ToList();

P.S。 我不想在开始时从tbl_books获取所有行

您能否建议解决此问题。谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用||代替Union

db.tbl_books
  .Where(b => book_ids.contains(b.id) || 
              subject_ids.contains(b.subject_id)))
  .ToList();

答案 1 :(得分:0)

试试这个:

var selectedBooks = db.tbl_books.where(b=> book_ids.contains(b.id) || subject_ids.contains(b.subject_id)).ToList();

答案 2 :(得分:0)

试试这个:

 var query = (from a in db.tbl_books 
 where a.book_ids == b_id && a.subject_ids == sub_id 
 select new{
      a.[column_name],
      a.[column_name],
      a.[column_name],
      //columns you want to retrieve
 }).ToList();

 var query = (from a in db.tbl_books 
 where a.book_ids == b_id || a.subject_ids == sub_id 
 select new{
      a.[column_name],
      a.[column_name],
      a.[column_name],
      //columns you want to retrieve
 }).ToList();

取决于你想要完成的事情。希望它可以帮到你。