有条件地调用 StartsWith/EndsWith 的最佳方式 [英] Best way of calling either StartsWith/EndsWith conditionally

查看:31
本文介绍了有条件地调用 StartsWith/EndsWith 的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似下面的方法:

I have a method similar to the following:

StringComparison comparison = StringComparison.CurrentCultureIgnoreCase;

switch(SearchType)
{
case SearchType.Contains:
list = list.Where(a => a.Reference.Contains("test",comparison));
break;

case SearchType.StartsWith:
list = list.Where(a => a.Reference.StartsWith("test",comparison));
break;

case SearchType.EndsWith:
list = list.Where(a => a.Reference.EndsWith("test",comparison));
break;
}

你可能猜到 SearchType 是我的自定义枚举.

As you can probably guess SearchType is a custom enum I have.

有没有更简单的方法可以做到这一点,可能是使用反射?多个开关看起来有点难看.

Is there an easier way of doing this, possibily using reflection? The multiple switches seem a bit ugly.

推荐答案

哪一部分不容易?

我想你可以为每个枚举创建一个类,从一个通用的 SearchType 接口继承并实现一个名为 ProcessList 的函数 - 不确定哪个列表可以提供更好的功能.

I guess you could have a class for each enum instead, inherit from a common SearchType interface and implement a function called ProcessList - not sure what list is to offer a better function.

有点像..

interface SearchType
{
   object ProcessList(object list, string text);
}

class Contains : SearchType
{
   object ProcessList(object list, string text)
   {
      list = list.Where(a => a.Reference.Contains(text, StringComparison.CurrentCultureIgnoreCase));
   }
}

需要为每个枚举类型做一个类.

Need to do a class for each enum type.

然后你需要像这样设置 SearchType 变量...

Then you would need to set the SearchType variable like this...

SearchType searchType = new Contains();//or something else

然后你的开关可以用这个替换......

and your switch could then be replaced with this...

list = searchType.ProcessList(list, "test");

...在编码方面并不是很容易,但是你得到了一个更易读的代码,而不是开关.

...Not really easier in terms of coding, but you get a more readable code instead of the switch.

这篇关于有条件地调用 StartsWith/EndsWith 的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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