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 Query
- 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
- How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n
- 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?
- How to use LINQ to query list of strings that do not contain substring entries from another list
- How do I get results from a Linq query in the order of IDs that I provide?
- Creating a LINQ query that will include all entries from the current week excluding today and yestreday
- How to return query results from method that uses LINQ to SQL
- how to get all non null values from array in c#
- How to best handle a search query that includes 0 to 3 parameters/filters but using a single LinQ to Entities expression
- How to filter linq query based on all of the values of one property from another list
- dynamic linq query - OrderBy with properties that are null
- Search in all childrens that inherit from a parent using EF / Linq
- How to create a linq lambda join query that pulls results even though there null results?
- How do I call a method from within a linq query that is retrieving from an Entity Framework model
- Include null cells in Linq query from DB in C# code
- How to remove NULL columns from a LINQ query for ObjectDataSource
- how to write Like Query for search Username from database in LINQ and ADO.NET
- How can I simplify (speed up) the selecting query from a database that contains more than 1 million records using LINQ
- List of objects where the object contains an array - how to use LINQ to search through all objects for a value in that array
- How to search with LINQ entites having string[] array properties and find these containing any of string from string[] array?
- how to fetch data from database using linq query for relationship 1:N and N:N (between 3 entity) in asp.net mvc EF code first?
- Dynamic linq query that Contains ALL from another list
- How to retrieve a List of Lists of strings that are not null or whitespace from a DataGridView using Linq
- How to generate XML from LINQ query
- how to use LINQ to search for all user names that Starts With ("john")?
- How to create a Dynamic Query when there's a condition that won't use all fields in the where section with LinQ
- LINQ query to extract all answers that contain any keyword from a list
More Query from same tag
- Group by on IEnumerable<DataRow>
- LINQ to Objects - Initialising lists
- WebAPI Get() method to return list of all records matching criteria
- How can i search partial part of a field using a list in LINQ?
- Linq problem: The expression of type 'System.String[]' is not a sequence
- How IEnumerable.Except() works?
- only update 1 column with linq
- Filtering a list of objects without linq c#
- How do I quickly create a new collection of objects from a collection of larger objects?
- How can I create a conditional where clause using LINQ
- Fastest Approach to Finding Number of Unique Members in a List
- linq for 2 dimensional array with all
- Dynamic Create Func<T,TR> C#
- Set combobox with long datasource
- Sorting by capital letters first
- Check value of one item of tuple from other item
- Using navigation properties in LINQ query causes problems such as relationship multiplicity
- How to do WHERE IN in linq
- How to Access a Field or attribute from a many to many table using Linq?
- LINQ IQueryable: Set 1 Parameter to accept Where Clause
- Entity Framework Linq to Object Mapping
- C# Linq Query - Extracting multiple groups from a collection (nested groups?)
- c#/linq data grouping
- Linq to Select Parent Objects Where Child Objects Dont contain value
- F# missing LINQ functions
- LINQ: Get a total count from a nested list inside projection
- First / FirstOrDefault not working as I would expect
- Troubleshooting LINQ Query Performance in ASP.NET MVC
- Case insensitive string compare in LINQ-to-SQL
- Linq query with two many-many relationships