带有可选WHERE选项的Linq [英] Linq with optional WHERE options

查看:33
本文介绍了带有可选WHERE选项的Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .Net function that accepts 3 parameters, all optional. Something like this:

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

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

My question is, what is the best way to do the where part. Would the best be to create dynamic linq? What's the best pattern, within linq, to have optional where parameters?

所以,在 SQL 中,是这样的:

So, in SQL, something like this:

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

但是我希望可以在linq中找到一种更整洁,更可接受的模式.

But I am hoping there a neater, more acceptable pattern for doing this within linq.

推荐答案

束缚 Where 子句并检查是否为空

Chain Where clauses with checking for 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();

替代方法是仅在需要时添加条件

Alternative approach would be to add conditions only when you need them

var query = context.MyTable;

if (color != null) query = query.Where(t => t.Color == color);
if (size != null) query = query.Where(t => t.Size == size);
if (name != null) query = query.Where(t => t.Name == name);

var result = query.ToList();

这篇关于带有可选WHERE选项的Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆