编写基于条件的 if 语句的优雅方式
我试图根据一组标准在列表中查找对象。基本逻辑如下所示
for (objectx obj : list)
{
if (object.property1 > criteria1)
//accept object
else (object.property1 == criteria1)
{
if (object.property2 > criteria2)
//accept object
else (object.property2 == criteria2)
{
if (object.property3 > criteria3)
... etc
}
}
}
有没有一种优雅的方法来简化这个混乱?
I'm trying to find an object in a list based on a set of criteria. The basic logic looks like this
for (objectx obj : list)
{
if (object.property1 > criteria1)
//accept object
else (object.property1 == criteria1)
{
if (object.property2 > criteria2)
//accept object
else (object.property2 == criteria2)
{
if (object.property3 > criteria3)
... etc
}
}
}
Is there an elegent way to simplify this mess?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将创建一个方法来检查所有属性,然后在循环中您可以简单地说:
I would create a method that checks all of the properties then inside your loop you can simply say:
添加以您的业务逻辑命名的方法可能会有所帮助。然后阅读代码应该像英语一样读起来,而实际的比较在其他地方。这也让思考变得更容易。
Adding methods named after your business logic may help. Then reading the code should read like english and the actual comparisons are somewhere else. It makes it easier to think about too.
如果您想做像我之前那样的事情,那会有所帮助。我想像你一样使用 NHibernate 搜索数据库中的对象。我创建了查询对象来收集用户输入的每个条件。当我在查询对象上设置相关属性时,我添加了这样的条件。
如果你只想过滤内存中的对象。您还可以使用规范模式。
If you want to do something like I did before that can help. I wanted to search for objects in database with NHibernate like you did. I created Query object to collect every criteria entered by user . And When I set the related property on Query object I added this criteria like this.
If you just want to filter objects in memory. You can also use Specification Pattern.