开发者

Is there a way to simplify this 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开发者_StackOverflow.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;
    }
}


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());


You can make one where clause:

where 
     (queueTextMessaging || ev.QueueTypeEnumText != QueueType.TextMessage.ToString())
   &&(queueEmail || ev.QueueTypeEnumText !=QueueType.Email.ToString())


var _filteredEvents =
  from ev in _events where (
    queueTextMessaging || ev.QueueTypeEnumText != QueueType.TextMessage.ToString() &&
    queueEmail || ev.QueueTypeEnumText !=QueueType.Email.ToString())
  select ev;


I would simply create a Method testing the condition for you

var _filteredEvents = from ev in _events where Test(queueEmail, queueTextMessaging, ev) select ev;

...

bool Test(bool foo, bool bar, Event ev) {...}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜