How can I convert the following linq queries to a (Having) like in SQL

asp.net-mvc-5.1 c# dynamic-linq entity-framework linq

Question

My intentions are to aggregate the results instead of narrow them down.

if (Request.QueryString["VenueType"] == null)
    Renders = _renderContext.Renders;
else
{
    List<int> venueTypeIds = Request.QueryString["VenueType"].Split(',')
        .Select(int.Parse).ToList();
    Renders = _renderContext.Renders.Where(v => venueTypeIds.Contains(v.VenueTypeId));
}

// SECOND CRITERION:
if (Request.QueryString["SearchTerm"] != null)
    Renders = Renders.Where(r => r.Title.ToLower()
        .Contains(Request.QueryString["SearchTerm"].ToLower()));

// ADDITIONAL CRITERION:
if (Request.QueryString["EventType"] != null)
{
    List<int> eventTypeIds = Request.QueryString["EventType"].Split(',')
        .Select(int.Parse).ToList();
    Renders = Renders.Where(w => eventTypeIds.Contains(w.EventTypeId));
}

if (Request.QueryString["DisplayFormat"] != null)
{
    List<int> displayFormatIds = Request.QueryString["DisplayFormat"].Split(',')
        .Select(int.Parse).ToList();
    Renders = Renders.Where(w => displayFormatIds.Contains(w.DisplayFormatId));
}

The Query Strings are coming from groups of checkboxes which may have one to many options. The results I am trying to return should not narrow down after the first set of criteria but instead return more results.

Question: How do I use either a where clause or GroupBy clause to get an aggregate of returned items rather than to narrow my returned items?

1
-3
10/27/2014 8:42:05 PM

Accepted Answer

If I understand your question correctly you could build your results gradually, something like this (code reduced for brevity)...

IQueryable query = from x in Context.Stuff
                   select x;

List<Stuff> output = List<Stuff>();

output = query.Where(r => r.Title).Contains("SearchTerm")).ToList();
output += query.Where(r => r.Title).Contains("DifferentSearchTerm")).ToList();

See this So post for how to perform an explicit Group By in Linq, although in my humble opinion given the complexity of your criteria it would be fairly unmaintainable.

-1
5/23/2017 11:57:10 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow