Simulating WHERE X OR Y Query in LINQ

By Peter Bromberg

There is no "WHERE OR" operator in LINQ. However, by constructing a UNION that combines the results of two or more WHERE operators, you can get the results you want.

The example method returns all Quotation objects where either the QuotationText or the Subject contain the search term:

/// <summary>
/// Gets quotes matching either subject or text in quote.
/// </summary>
/// <param name="like">The search term</param>
/// <returns>List<Quotation></returns>
public static List<Quotation> GetQuotesBySubjectOrTextInQuote(string like)
{
    var foundQuotes= Quotes.Where(x => x.QuotationText.ToLower().Contains(like.ToLower())).Union(Quotes.Where(x => x.Subject.ToLower().Contains(like.ToLower())).ToList());
      return foundQuotes.ToList();
}

Simulating WHERE X OR Y Query in LINQ  (656 Views)