避免在动态条件下使用linq多次浏览列表(过滤器) [英] Avoid to browse a list multiple time with linq, with dynamic conditions (filter)

查看:44
本文介绍了避免在动态条件下使用linq多次浏览列表(过滤器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含Article个对象的列表. 该对象的参数是

I have a list with Article objects. Parameters for this object are

类别,描述,状态,类别

Category, Description, Status, Class

用户可以使用所需的组合来过滤列表.仅描述,或类别+类,等等.

The user can filter the list with the combinaison he wants. Only Description, or Category + Class, an so on.

因此,如果用户选择一个条件,我将得到一个int> = 0,否则我将得到-1.

So if the user choose a criterion i'll get an int >= 0, otherwise i'll get -1.

例如,如果他选择使用StatusCategory进行过滤,我会得到

For example if he choose to filter with Status and Category, i'll get

FilterCategory = x,FilterDescription = -1,FilterStatus = y,FilterClass = -1

FilterCategory = x, FilterDescription = -1, FilterStatus = y, FilterClass = -1

我过滤列表的方法如下:

My way to filter the list is the following:

if (FilterCategory != -1)
    list = list.Where(a => a.Category == FilterCategory);
if (FilterDescription != -1)
    list = list.Where(a => a.Description == FilterDescription);
if (FilterStatus != -1)
    list = list.Where(a => a.Status == FilterStatus);
if (FilterClass != -1)
    list = list.Where(a => a.Class == FilterClass);

通过这种方式,我必须对列表进行4次迭代,这对于很多项目而言效率不高.我将浏览列表一次,并在唯一的位置检查4个条件.但是我不知道如何在特定条件下做到这一点!= -1.

In this way, i have to iterate the list 4 time, it's not efficient with a lot of items. I would browse the list once, and check the 4 condition in an unique where. But i don't know how to do that with the specific condition != -1.

谢谢

推荐答案

您可以执行以下操作:

if (FilterCategory != -1)
    list = list.Where(a => a.Category == FilterCategory);

等效于:

list = list.Where(a => FilterCategory == -1 || a.Category == FilterCategory);

然后查询为:

list = list.Where(a => (FilterCategory == -1 || a.Category == FilterCategory)
                    && (FilterDescription == -1 || a.Description == FilterDescription)
                    && (FilterStatus == -1 || a.Status == FilterStatus)
                    && (FilterClass == -1 || a.Class == FilterClass));

但是我真的怀疑它会提高您的枚举性能.

But I really doubt it will improve your enumeration performance.

这篇关于避免在动态条件下使用linq多次浏览列表(过滤器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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