有没有办法简化这个linq

时间:2011-03-14 18:27:56

标签: c# linq

我有2个bool标志,需要相应地过滤我的集合。必须有一个更清洁的方法来做到这一点。如果有人能指出我正确的方向,我会很感激。感谢。

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;
    }
}

4 个答案:

答案 0 :(得分:9)

由于LINQ使用延迟执行,您只需将Where()扩展名更改为您的对象,然后随时重新分配:

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

答案 1 :(得分:2)

您可以制作一个where子句:

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

答案 2 :(得分:2)

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

答案 3 :(得分:0)

我只想创建一个方法来测试你的条件

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

...

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