I am working on a query where I want to retrieve data including multiple int? keys.
My output Dto:
public class FilterParamsDto {
public int? StudentId { get; set; }
public int? NationalityId { get; set; }
public int? CountryId { get; set; }
public int? SchoolCountryId { get; set; }
public int? SchoolStateId { get; set; }
public int? SchoolCityId { get; set; }
.... More keys
}
I used following queries
var value = from y in data
where dto.CountryId == null
? y.CountryId != null
: y.IntakeId == dto.CountryId && dto.StudentId == null
? y.StudentId != null
: y.StudentId == dto.StudentId && dto.SchoolCityId == null
? y.SchoolCityId != null
: y.SchoolCityId == dto.SchoolCityId
select y;
What I want to Achieve:
I want to make a method where if any property have some value I want to filter data based on that particular property and if there is not any value I want to filter data based on another properties who do have some value.
if any property have 0 value I want to skip filter because if any property have 0 value so the data wont’ match and i am not going to receive any data using || the data is not getting filtered as per required condition.
EDIT 1 There are three possibilities either all properties have some values, some properties caring values, all the properties caring values.
the required logic should be like if first where executed then another where should be executed on updated values and so on…
3
Answers
To give you just one example, do it like this
Add as many conditions as you want.
Well, if you have many properties like the above and have multiple versions of this kind of filter operation I would suggest building a dynamic expression to filter your collections. This approach has one assumption: the entity that is queried and the dto has the same property names and similar types.
Fiddle
To filter by the first available filter property, you can write (I replaced
dto
byfilter
andy
byd
to make it clearer):To filter by all available filters:
The test
(d.CountryId ?? d.IntakeId) == filter.CountryId
comparesd.CountryId
if it is not null and otherwised.IntakeId
withfilter.CountryId
.According to the documentation of ?? and ??= operators (C# reference):