Linq带有可选的WHERE选项

时间:2015-10-04 07:23:18

标签: c# sql linq

我有一个接受3个参数的.Net函数,都是可选的。像这样:

public List<MyObject> Search(string colour, string size, string name)
{
     var result = (from c in MyTable where .... select c).ToList();     
}

我的问题是,where部分的最佳方法是什么?最好是创建动态linq吗?在linq中,具有可选where参数的最佳模式是什么?

所以,在SQL中,像这样:

SELECT *
FROM MyTable
WHERE (@colour <> '' AND colour = @colour)
  AND (@size <> '' AND size = @size)
  AND (@name <> '' AND name = @name)

但我希望在linq中有更简洁,更可接受的模式。

6 个答案:

答案 0 :(得分:3)

在这种情况下,我建议您使用PredicateBuilder生成查询。您可以从此处复制代码,也可以安装LinqKit Nuget Package。

使用此代码可以动态生成动态查询,并阻止您编写大量的if / else语句。

声明如......

p => p.Price > 100 &&
 p.Price < 1000 &&
 (p.Description.Contains ("foo") || p.Description.Contains ("far"))

将由这种代码生成:

var inner = PredicateBuilder.False<Product>();
inner = inner.Or (p => p.Description.Contains ("foo"));
inner = inner.Or (p => p.Description.Contains ("far"));

var outer = PredicateBuilder.True<Product>();
outer = outer.And (p => p.Price > 100);
outer = outer.And (p => p.Price < 1000);
outer = outer.And (inner);

我认为这是相当简洁的,它也会让你了解表达式的强大程度。

答案 1 :(得分:3)

只需链接Where子句并检查null

var result = context.MyTable
                    .Where(t => color == null || color == t.Color)
                    .Where(t => size == null || size == t.Size)
                    .Where(t => name == null || name == t.Name)
                    .ToList()

答案 2 :(得分:2)

var results = olstOfObjects.Where(x => 
    (x.size == size || x.size == "") &&
    (x.color == color || x.color == "") &&
    (x.name == name || x.name == "")).ToList();

答案 3 :(得分:0)

您可以在Search方法中执行以下操作:

var query = from c in MyTable select c;
if (!String.IsNullOrEmpty(colour))
  query = from c in query where c.colour == colour select c;
if (!String.IsNullOrEmpty(size))
  query = from c in query where c.size == size select c;
if (!String.IsNullOrEmpty(name))
  query = from c in query where c.name == name select c;
return query.ToList();

答案 4 :(得分:0)

怎么样:

public List<MyObject> Search(string colour, string size, string name)
{
    IEnumerable<MyObject> result = MyTable;

    if(colour != null)
        result = result.Where(o => o.Colour == colour);

    if(size != null)
        result = result.Where(o => o.Size == size);

    ...

    return result.ToList();
}

答案 5 :(得分:0)

这里有一个包含所有条件的查询:

public List<object> Search(string colour, string size, string name)
{
    var query = from c in MyTable
        where
            (string.IsNullOrEmpty(colour) || c.colour == colour) &&
            (string.IsNullOrEmpty(size) || c.size == size) &&
            (string.IsNullOrEmpty(name) || c.name == name)
        select c;

    return query.ToList();
}