I have been trying to convert a simple if else to a linq statement.
The if else statement goes something like this:
if ( MessageStatus = 1 )
then MessageCount > 0
else if ( MessageStatus = 2 )
then MessageCount = 0
else
do nothing
This is what I have in my linq so far and it didn't query out the data I wanted
var query = _context.Message
.Where(c => request.MessageStatus.Equal(2) ? c.MessageCount.Equals(0) :
request.MessageStatus.Equal(1) ? c.MessageCount > 0 :
request.MessageStatus.Equal(0));
It should be able to return rows of data but instead it return nothing.
Where does the problems lie at?
Thanks
CodePudding user response:
What you're asking about is conditional filtering. request.MessageStatus
is a value you know before you execute the query, so you can use it to define which Where
to add to the query.
This works by creating a IQueryable<...>
for the whole data set (your table), then adding on the Where
that you want based on some condition. It's important to note that you're always doing query = query.Where(...);
, if you don't re-assign query
you lose the additional filter.
// "request" is defined earlier
IQueryable<Message> query = _context.Message; // might need .AsQueryable() here
if (request.MessageStatus == 1)
{
query = query.Where(r => r.MessageCount > 0);
}
else if (request.MessageStatus == 2)
{
query = query.Where(r => r.MessageCount = 0);
}
else
{
// assuming that this means "include all records",
// don't perform any additional filtering
// you don't need this "else"
}
List<Message> results = query.ToList();
It's also good to know that this pattern works outside of EF as well with basic IEnumerable
s and in memory collections.