简体   繁体   English

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

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

I have this piece of code as an Azure function app and I would like to know how can I best handle this if else part.我将这段代码作为 Azure function 应用程序,我想知道if else部分,我该如何最好地处理它。

There are like 100 Project with different customer name.有大约 100 个具有不同客户名称的项目。

What is the best way to do it?最好的方法是什么?

If one can show me with an example.如果有人能给我举个例子。

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 ) );

Read customer values:阅读客户价值:

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

Get config Value:获取配置值:

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; }
    }

Simple, use a dictionary:很简单,使用字典:

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

And then use a lookup:然后使用查找:

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

TryGetValue docs TryGetValue 文档

I have a bunch of extension methods for IDictionary<K, V> like this:我有一堆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];
    }
}

I can use this like so:我可以这样使用它:

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

Then your code becomes:然后你的代码变成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM