EMIE EMIE - 7 months ago 168
SQL Question

C# Dynamic Linq Where Clause

is there a way to dynamically build a Where clause in LINQ?

Example... today I query my sql db, and only ServerGroup A has issues. I return the fault codes for that group. Works. However, tomorrow, ServerGroup A & B have issues. I do not want to manually change my LINQ query, but have it dynamically add the new ServerGroup to the WHERE clause. Is this possible with LINQ? I've done it with a Sql query.

Greatly appreciate the assistance.

var query = referenceDt.AsEnumerable()
.Where(results => results.Field<string>("ServerGroup") == "A" ||
results.Field<string>("SeverGroup") == "B")
.GroupBy(results => new
{
FaultCode = results.Field<int>("FaultCode")
})
.OrderByDescending(newFaultCodes => newFaultCodes.Key.FaultCode)
.Select(newFaultCodes => new
{
FaultCode = newFaultCodes.Key.FaultCode,
Count = newFaultCodes.Count()
});

Answer

This is a perfect use case for .Contains()

var serverGroups = new string []{ "A", "B" }.ToList();

var query = referenceDt.AsEnumerable()
        .Where(results => serverGroups.Contains(results.Field<string>("ServerGroup")))
        .GroupBy(results => new
            {
                FaultCode = results.Field<int>("FaultCode")
            })
        .OrderByDescending(newFaultCodes => newFaultCodes.Key.FaultCode)
        .Select(newFaultCodes => new
        {
            FaultCode = newFaultCodes.Key.FaultCode,
            Count = newFaultCodes.Count()
        });

where serverGroups would be dynamically generated.

Comments