我正在寻找一些C#代码,这些代码可以帮助我解决最合适的模板,以便使用和枚举所有可用的模板
我有以下枚举
public enum TextTemplateTypeEnum
{
BookingConfirmationV1 = 1,
BookingConfirmationV2,
BookingConfirmationTescoV1,
BookingConfirmationV3,
BookingConfirmationTescoV2,
BookingConfirmationAsdaV1
}
然后我需要通过选择正确和最新的文本模板来解析要使用的模板,所以我将以下变量传递到函数中
string customerName = Tesco;
ReasonEnum reason = ReasonEnum.BookingConfirmation
使用该信息我需要选择最合适模板的最高V *,因此对于上述变量,它将是
TextTemplateTypeEnum.BookingConfirmationTescoV2
但是例如客户名称是
string customerName = Waitrose;
要返回的正确模板是
TextTemplateTypeEnum.BookingConfirmationV3
答案 0 :(得分:0)
好吧,您可以使用Enum.GetNames
在枚举中查找客户端名称,按最后一个字符对其进行排序,然后再次将其解析为枚举:
string client="Tesco";
var template=Enum.GetNames(typeof(TextTemplateTypeEnum))
.Where(x => x.Contains(client))
.OrderByDescending(o => o.Substring(o.Length - 1, 1))
.FirstOrDefault();
if (template==null)
{
template = Enum.GetNames(typeof(TextTemplateTypeEnum))
.Where(x => x.Length == 21)
.OrderByDescending(o => o.Substring(o.Length - 1, 1))
.FirstOrDefault();
}
TextTemplateTypeEnum t = (TextTemplateTypeEnum)Enum.Parse(typeof(TextTemplateTypeEnum), template);
但是这个实现有两个可能的问题。首先是当您达到版本10时会发生的情况,因为它将以V10
结束,并且不会按预期进行排序。另一个是“通用”模板。在这段代码中,我按尺寸(21)查看它们,但这不是很可靠。因此,为了使此代码有效,我建议您将通用模板名称更改为BookingConfirmationGenericV2
(这样您就可以查找“Generic”以获得正确的名称)并将版本更改为至少2位数({{1} })。
修改强>
好的,现在我意识到你有另一个枚举的原因。让我们看看这种方法是否适合你:
BookingConfirmationV01
用法:
static TextTemplateTypeEnum GetTemplate(string client,ReasonEnum reason)
{
string reasonString = Enum.GetName(typeof(ReasonEnum), reason);
string enumToSearch = reasonString + client;
var template = Enum.GetNames(typeof(TextTemplateTypeEnum))
.Where(x => x.Contains(enumToSearch))
.OrderByDescending(o => o.Substring(o.Length - 1, 1))
.FirstOrDefault();
if (template == null)
{
template = Enum.GetNames(typeof(TextTemplateTypeEnum))
.Where(x => x.StartsWith(reasonString) && x[reasonString.Length]=='V')
.OrderByDescending(o => o.Substring(o.Length - 2, 2))
.FirstOrDefault();
}
return (TextTemplateTypeEnum)Enum.Parse(typeof(TextTemplateTypeEnum), template);
}
对于10开启的版本,这将失败,这就是为什么我建议使用至少2位数的版本。