Alternative to if, else if

后端 未结 8 1053
后悔当初
后悔当初 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 11:48

    One more using LINQ and Dictionary

    var mapping = new Dictionary()
                            {
                                { "SWGAS.COM", "Southwest Gas" },
                                { "georgiapower.com", "Georgia Power" }
                                .
                                .
                            };
    
    return mapping.Where(pair => txtvar.BillText.IndexOf(pair.Key) > -1)
                  .Select(pair => pair.Value)
                  .FirstOrDefault();
    

    If we prefer empty string instead of null when no key matches we can use the ?? operator:

    return mapping.Where(pair => txtvar.BillText.IndexOf(pair.Key) > -1)
                  .Select(pair => pair.Value)
                  .FirstOrDefault() ?? "";
    

    If we should consider the dictionary contains similar strings we add an order by, alphabetically, shortest key will be first, this will pick 'SCE' before 'SCEC'

    return mapping.Where(pair => txtvar.BillText.IndexOf(pair.Key) > -1)
                  .OrderBy(pair => pair.Key)
                  .Select(pair => pair.Value)
                  .FirstOrDefault() ?? "";
    

提交回复
热议问题