使用几个可为空的条件过滤IEnumerable - 使用lambda表达式列出

时间:2014-04-03 09:24:41

标签: c# linq lambda where-clause conditional-statements

我使用的是.NET 4.5和VS 2012。

我有一个类模型(来自Xml Deserialize),我现在已经“过滤”了它。

我在几个条件下都没有值。

使用lambda表达式这是最好的做法吗?

我有这段代码:

    public static List<MyDto> ListarEntornosYContenidoEntorno(int? id, string name, int? id2, string name2, string entorno, bool? shouldBe, string mode)
    {
        IEnumerable<MyDto> list = Model.Environments;

        if (id.HasValue)
            list = list.Where(item => item.IdCiaDespliegue.Equals(id.Value));

        if (!name.IsNullOrWhiteSpace())
            list = list.Where(item => item.NombreCiaDespliegue.Equals(name));

        if (id2.HasValue)
            list = list.Where(item => item.IdContenidoEntorno.Equals(id2.Value));

        if (!name2.IsNullOrWhiteSpace())
            list = list.Where(item => item.ContenidoEntorno.Equals(name2));

        if (!entorno.IsNullOrWhiteSpace())
            list = list.Where(item => item.Entorno.Equals(entorno));

        if (shouldBe.HasValue)
            list = list.Where(item => item.DebeEtiquetar.Equals(shouldBe));

        if (!mode.IsNullOrWhiteSpace())
            list = list.Where(item => item.Modo.Equals(mode));

        return list.ToList();

    }

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作(不确定它是否更具可读性):

IEnumerable<MyDto> list = Model.Environments;

return list.Where(item => !id.HasValue                       || item.IdCiaDespliegue == id.Value)
           .Where(item => string.IsNullOrWhiteSpace(name)    || item.NombreCiaDespliegue == name)
           .Where(item => !id2.HasValue                      || item.IdContenidoEntorno == id2.Value)
           .Where(item => string.IsNullOrWhiteSpace(name2)   || item.ContenidoEntorno == name2)
           .Where(item => string.IsNullOrWhiteSpace(entorno) || item.Entorno == entorno)
           .Where(item => !shouldBe.HasValue                 || item.DebeEtiquetar == shouldBe)
           .Where(item => string.IsNullOrWhiteSpace(mode)    || item.Modo == mode)
           .ToList();

诀窍就是当你的选择器为null或为空时返回true,这样就不会过滤任何项目。

请注意,我已将所有.Equals替换为==,因为在这种情况下它们是等效的,==在我看来更具可读性。

答案 1 :(得分:1)

我已经为你提供了一种方法,可以将下面的内容概括为你的可以为止的整数;我相信你可以为琴弦做类似的事情。此外,您应该考虑更改API,以便此方法接受“过滤条件”或类似的列表。

var intMap = new Dictionary<int?, Func<Environment, int>> 
{
    { id, item => item.IdCiaDespliegue },
    { id2, item => item.IdContenidoEntorno },
    { entorno, item => item.DebeEtiquetar }
}

var list = Model.Environments;

foreach(var pair in intMap)
{
    if(pair.Key != null)
        list = list.Where(item => pair.Value(item).Equals(pair.Key.Value));
}