如何重构这个 if-else 条件,使其更简洁、更高效?

我有这段代码作为 Azure 函数应用程序,我想知道如何最好地处理这if else部分。

有像 100 个不同客户名称的项目。

最好的方法是什么?

如果有人可以给我举个例子。

string customerName = string.Empty;
foreach( var doc in result )
{
    var data =(JObject)JsonConvert.DeserializeObject( doc.ToString() );
    if( (string)data["Project"] == "HPD_Oid" )
    {
        customerName = "OPPO";
    }
    else if( (string)data["Project"] == "HPD_Oreal" )
    {
        customerName = "RealMe";
    }
    else
    {
        customerName = "OnePlus";
    }
    string partitionkeyValue = string.Concat( (string)data["class"], "|", (string)data["Project"], "|", customerName );
    data.Add( new JProperty( "PartitionKey", partitionkeyValue ) );

读取客户价值:

CustomerSection customer = GetConfiguration( context.FunctionAppDirectory, "CustomerSection.json" );

获取配置值:

private static CustomerSection GetConfiguration( string basePath, string fileName )
        {
            var config = new ConfigurationBuilder()
                   .SetBasePath( basePath )
                   .AddJsonFile( fileName, optional: false )
                   .Build();
            var customerNameOutput = new CustomerSection();
            config.GetSection( "ProjectCustomerMapping" ).Bind( customerNameOutput );
            return customerNameOutput;
        }

public class CustomerSection
    {
        public Dictionary<string, string> CustomerName { get; set; }
    }

回答

很简单,使用字典:

Dictionary<string, string> projectCustomerNameMapping = new Dictionary<string, string>()
{
{ "HPD_Oid", "OPPO" },
{ "HPD_Oreal", "RealMe" }
};

然后使用查找:

if (!projectCustomerNameMapping.TryGetValue((string)data["Project"], out customerName))
{
// if the value wasn't found in the dictionary, use the default
customerName = "OnePlus";
}

TryGetValue 文档

  • +1,尽管我想补充一点,映射的内容可能应该移动到数据库或配置文件中。

以上是如何重构这个 if-else 条件,使其更简洁、更高效?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>