Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to simplify this linq

Tags:

c#

linq

I have 2 bool flags and need to filter my collection accordingly. There has to be an cleaner way to do this. If anyone can point me in the right direction I'd appreciate it. Thanks.

var _filteredEvents = from ev in _events 
                      select ev;
if (!queueEmail) // don't queue email
{
    if (!queueTextMessaging) // don't queue textmessaging
    {
        _filteredEvents = from ev in _events
                              where ev.QueueTypeEnumText != QueueType.TextMessage.ToString() 
                                && ev.QueueTypeEnumText !=QueueType.Email.ToString()
                              select ev;
    }
    else
    {
         _filteredEvents = from ev in _events
                              where ev.QueueTypeEnumText != QueueType.Email.ToString()
                              select ev;
    }
}
else //queue email
{
    if (!queueTextMessaging) //don't queue textmessaging
    {
        _filteredEvents = from ev in _events
                          where ev.QueueTypeEnumText != QueueType.TextMessage.ToString()
                          select ev;
    }
}
like image 586
mokumaxCraig Avatar asked Mar 14 '11 18:03

mokumaxCraig


2 Answers

Since LINQ uses deferred execution, you can just change the Where() extensions onto your object, and reassign it as you go:

var _filteredEvents = _events; 
if (!queueEmail)
     _filteredEvents =  _filteredEvents.Where(ev => ev.QueueTypeEnumText != QueueType.Email.ToString());
if (!queueTextMessaging)
     _filteredEvents =  _filteredEvents.Where(ev => ev.QueueTypeEnumText != QueueType.TextMessage.ToString());
like image 192
Reed Copsey Avatar answered Sep 21 '22 19:09

Reed Copsey


You can make one where clause:

where 
     (queueTextMessaging || ev.QueueTypeEnumText != QueueType.TextMessage.ToString())
   &&(queueEmail || ev.QueueTypeEnumText !=QueueType.Email.ToString())
like image 38
Mark Sowul Avatar answered Sep 23 '22 19:09

Mark Sowul