score:2
Couldn't you just do something like this?
[HttpPost]
public List<TestRecord> Search(TestRecord testRecord){
List<TestRecord> records = _db.TestRecords
.Where(tr => String.IsNullOrEmpty(testRecord.TestType) ? true : tr.TestType == testRecord.TestType)
.Where(tr => String.IsNullOrEmpty(testRecord.Part.Name) ? true : tr.Part.Name == testRecord.Part.Name)
//etc...
.ToList();
return records;
}
Essentially only filter if the input is there for every field in 1 big query?
score:0
The query doesnt have to be one single chain, you can split it up and insert some if
:
var query = _db.TestRecords.AsQueryable();
if (string.IsNullOrEmpty(testRecord.TestType))
{
query = query.Where(x => x.TestType == testRecord.TestType);
}
if (string.IsNullOrEmpty(testRecord.Part.Name))
{
query = query.Where(x => x.Part.Name == testRecord.Part.Name);
}
// or, you can use an intermediate variable before returning to debug
return query.ToList();
score:0
I usually use an extension method like this:
public static IQueryable<T> Where<T>(this IQueryable<T> that, object notNull, Expression<Func<T, bool>> predicate)
{
if (!string.IsNullOrWhiteSpace(notNull?.ToString()))
{
return that.Where(predicate);
}
return that;
}
Then you can compose your LINQ query like this:
return s.Query()
.Where(onlyStatus, p => p.Status == onlyStatus)
.OrderByDescending(p => p.CreatedDate)
.ToList();
score:0
If you have only one class that has this requirement with only a limited number of properties, say less than 20, I wouldn't bother creating a generic solution for this. Code a Where
that checks all properties. This has the advantage that if in future someone changes or removes a property your compiler will complain.
A nice solution would be to give your class an extension function:
public static bool HasNullProperties(this MyClass x)
{
return x.Name == null
&& x.Location == null
&& x.OrderSize == null
...;
}
public static IEnumerable<MyClass> WhereHasNullProperties(this IEnumerable<MyClass> source)
{
return source.Where(item => item.HasNullProperties();
}
Usage somewhere in a LINQ statement
var result = dbContext.MyItems.WhereHasNullProperties()
.GroupBy(...)
.Select(...);
If you want a full proof solution that works on several classes, consider designing an interface:
interface IHasNullProperties
{
bool HasNullProperties {get;}
}
Your LINQ function will be:
public static IEnumerable<TSource> WhereHasNullProperties<TSource>(
this IEnumerable<TSource> source)
where TSource : IHasNullProperties
{
return source.Where(item => item.HasNullProperties();
}
Finally a relatively slow method would be to use reflection: for any class, get all its get-properties that are nullable and see if any of them has a null value:
static bool HasNullPrperties<TSource>(this TSource source)
where TSource : class
{
// Take the type of the source, and get all properties of this type
var result = source.GetType().GetProperties()
// keep only the readable properties (so you can do GetValue)
// and those properties that have a nullable type
.Where(property => property.CanRead
&& Nullable.GetUnderlyingType(property.Type) != null)
// for every of this properties, ask the source object for the property value:
.Select(property => property.GetValue(source))
// and keep only the properties that have a null value
.Where(value => value == null);
// return true if source has any property with a null value
// = if there is any value left in my sequence
.Any();
return result;
}
Source: stackoverflow.com
Related Articles
- How to generate a LINQ query that queries all non-null properties from a search page model
- How can I set properties on all items from a linq query with values from another object that is also pulled from a query?
- Linq query that returns all records if the search item is null or empty
- dynamic linq query - OrderBy with properties that are null
- Include null cells in Linq query from DB in C# code
- linq query that joins results from three other queries
- Linq to SQL - Ignore search parameters that are null or zero
- Which LINQ query to select rows from 1 table that are not in another table
- How to Query from Asp.Net Profile Properties using LINQ
- linq - how do you do a query for items in one query source that are not in another one?
- EF6 Query Criteria using object properties that aren't null
- How to use LINQ to query list of strings that do not contain substring entries from another list
- using linq query to find value that differs from previously found value
- Linq intersect or join to return items from one collection that have matching properties to another?
- How do I get results from a Linq query in the order of IDs that I provide?
- Updating the original reference to an object that was returned from a linq query
- creating Linq to sqlite dbml from DbLinq source code
- Why does this LINQ query assign a value of 1 to a NULL value from the database?
- C# LINQ : Dynamically create property and values that includes sum of a value from a grouped query
- Linq for selecting elements from list 1 that exist on list 2 by comparsion between 2 properties values
- Get the "latest" datetime from a large linq query that currently returns every record that has a datetime
- Updating LINQ to SQL but the query i have is from a join? Can't update using query that uses a join?
- Generate string from Grouping Linq Query
- combine 2 queries from the same table into one linq query
- Linq query with select needed to get specific properties from a list
- Creating a LINQ query that will include all entries from the current week excluding today and yestreday
- EF Core Linq Query to Select Rows That Match From a List of Possibilities
- Create a entity framework LINQ group join query to return a subset of properties from DTO and a list of another DTO, ASP.net core
- Linq Query from textboxes that might be empty (Coalesce)
- How to return query results from method that uses LINQ to SQL
- LINQ to Entities does not recognize the method in query
- Where Contains from two function calls
- LINQ Query Not Selecting Files
- Referencing DataRows by column name in a LINQ query, then filter via mapping with another dataset
- Linq : Checking how many times the same value consecutively
- Is Lazy Loading really bad?
- Create a class type in code in .net c#
- Best practices re: LINQ To SQL for data access
- How to retrieve a control with a certain property from a collection of Controls?
- Handling NULL Parameters in LINQ Queries
- What's the best way to implement a many-to-many mapping in XML and C#?
- Linq Distinct() or GroupBy() method is not working in below scenario
- what is the difference between LINQ and ADO.net
- Construct LambdaExpression for nested property from string
- How to obtain a list of elements contained in multiple list using LINQ?
- Select 2 or more columns on DataTable using LINQ
- Divide a large IEnumerable into smaller IEnumerable of a fix amount of item
- Removing characters from strings with LINQ
- Unknown Select(?) of System Data Entity DbSet
- How to concat multiple selects with LINQ?