Alternative to if, else if

后端 未结 8 1060
后悔当初
后悔当初 2021-02-07 11:20

I have a lot of if, else if statements and I know there has to be a better way to do this but even after searching stackoverflow I\'m unsure of how to do so in my particular cas

8条回答
  •  青春惊慌失措
    2021-02-07 12:03

    Why not use everything C# has to offer? The following use of anonymous types, collection initializers, implicitly typed variables, and lambda-syntax LINQ is compact, intuitive, and maintains your modified requirement that patterns be evaluated in order:

    var providerMap = new[] {
        new { Pattern = "SWGAS.COM"       , Name = "Southwest Gas" },
        new { Pattern = "georgiapower.com", Name = "Georgia Power" },
        // More specific first
        new { Pattern = "City of Austin"  , Name = "City of Austin" },   
        // Then more general
        new { Pattern = "Austin"          , Name = "Austin Electric Company" }   
        // And for everything else:
        new { Pattern = String.Empty      , Name = "Unknown" }
    };
    
    txtVar.Provider = providerMap.First(p => txtVar.BillText.IndexOf(p.Pattern) > -1).Name; 
    

    More likely, the pairs of patterns would come from a configurable source, such as:

    var providerMap =
        System.IO.File.ReadLines(@"C:\some\folder\providers.psv")
        .Select(line => line.Split('|'))
        .Select(parts => new { Pattern = parts[0], Name = parts[1] }).ToList();
    

    Finally, as @millimoose points out, anonymous types are less useful when passed between methods. In that case we can define a trival Provider class and use object initializers for nearly identical syntax:

    class Provider { 
        public string Pattern { get; set; } 
        public string Name { get; set; } 
    }
    
    var providerMap =
        System.IO.File.ReadLines(@"C:\some\folder\providers.psv")
        .Select(line => line.Split('|'))
        .Select(parts => new Provider() { Pattern = parts[0], Name = parts[1] }).ToList();
    

提交回复
热议问题