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

How to refactor this if-else condition to make it cleaner and more efficient?

我将这段代码作为 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 docs

我有一堆 IDictionary<K, V> 的扩展方法,如下所示:

public static class IDictionaryExt
{
    public static Func<K, V> Map<K, V>(this IDictionary<K, V> source, Func<V> @default)
    {
        return key => (key == null || !source.ContainsKey(key)) ? @default() : source[key];
    }
}

我可以这样使用:

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

那么你的代码就变成了:

string customerName = projectCustomerNameMapping((string)data["Project"]);