Question

I would like to ask the difference of the 2 statements below:

Statement 1:

var query = context.GetQueryable<CustomSearchResultItem>()
                        .Where(item => item.ContentTitle.Contains("lorem") || item.ContentShortDescription.Contains("lorem"))

Statement 2:

var query = context.GetQueryable<CustomSearchResultItem>();
var predicate = PredicateBuilder.True<CustomSearchResultItem>();
predicate = predicate.And(item => item.ContentTitle.Contains(searchfields.searchKeyword));
predicate = predicate.Or(item.ContentShortDescription.Contains(searchfields.searchKeyword));
queryResults = query
            .Where(predicate)

I have executed both the statement in sitecore, but it return different results.

Was it helpful?

Solution

While I have no experience with Sitecore, it appears to employ a variation of Albahari's PredicateBuilder which I do have experience with. The queries presented are roughly identical.

The second query would generate a predicate similar to:

(true && item.ContentTitle.Contains("lorem")) || 
    item.ContentShortDescription.Contains("lorem") 

Where the first is obviously:

(item.ContentTitle.Contains("lorem") || 
    item.ContentShortDescription.Contains("lorem"))

The results should be identical but to be sure you could do something like:

Expression<Func<CustomSearchResultItem, bool> predicate = item =>
    item.ContentTitle.Contains("lorem") ||
    item.ContentShortDescription.Contains("lorem");

System.Diagnostics.Trace.WriteLine(predicate);

var query = context.GetQueryable<CustomSearchResultItem>()
                    .Where(predicate)

and:

var query = context.GetQueryable<CustomSearchResultItem>();
var predicate = PredicateBuilder.True<CustomSearchResultItem>();
predicate = predicate.And(item =>
    item.ContentTitle.Contains(searchfields.searchKeyword));

// Assumptions made to make the sample compileable.
predicate = predicate.Or(item => 
    item.ContentShortDescription.Contains(searchfields.searchKeyword));

System.Diagnostics.Trace.WriteLine(predicate);

queryResults = query.Where(predicate)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top