[英]How to refactor this if-else condition to make it cleaner and more efficient?
我將這段代碼作為 Azure function 應用程序,我想知道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";
}
我有一堆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"]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.