How to refactor existing C# code using c# new syntaxes ?

T.Zacks 3,996 Reputation points
2022-07-08T12:17:22.43+00:00

How to refactor below code using c# new syntaxes which would minimize the line of code and also code looks compact & professional.

I have few quarters separated by comma. i have to write each quarter in a specific row of excel sheet by EPPlus. those quarter would look like below image. here i am pasting my image which give you idea what i am trying to print in each cell of a specific row in excel sheet. please have a look at this image.

219017-pp.png
Sample Code

i am writing like 1Q20A 2Q20A............4Q24E. this way i need to print. i want to refactor existing code to minimize number of line.

string periods="1Q 2020A,2Q 2020A,3Q 2020A,4Q 2020A,2020 FYA,1Q 2021A,2Q 2021A,3Q 2021A,4Q 2021A,2021 FYA,1Q 2022A,2Q 2022E,3Q 2022E,4Q 2022E,2022 FYE,1Q 2023E,2Q 2023E,3Q 2023E,4Q 2023E,2023 FYE,1Q 2024E,2Q 2024E,3Q 2024E,4Q 2024E,2024 FYE"  
  
int Counter=3;  
string startperiod = "", endperiod = "";  
lstperiods = periods.Split(',').Select(a=> a.ToString()).ToList();  
foreach(var p in lstperiods)  
{  
 year = Convert.ToInt32((p.Replace("A", "").Replace("E", "").Replace("FY", "").Replace("1Q", "")  
 .Replace("2Q", "").Replace("3Q", "").Replace("4Q", "")).Trim());  
  
 if (p.Contains("A"))  
 {  
 if(p.Contains("1Q") || p.Contains("2Q") || p.Contains("3Q") || p.Contains("4Q"))  
 {  
 ws.Cells[7, Counter].Value = p.Substring(0, 2) + year.ToString().Substring(0, 2) + "A";  
 }  
 else if (p.Contains("FY"))  
 {  
 ws.Cells[7, Counter].Value = "FY"+ p.Substring(0, 2) +  "A";  
 }  
 }  
 else if (p.Contains("E"))  
 {  
 if (p.Contains("1Q") || p.Contains("2Q") || p.Contains("3Q") || p.Contains("4Q"))  
 {  
 ws.Cells[7, Counter].Value = p.Substring(0, 2) + year.ToString().Substring(0, 2) + "E";  
 }  
 else if (p.Contains("FY"))  
 {  
 ws.Cells[7, Counter].Value = "FY" + p.Substring(0, 2) + "E";  
 }  
 }  
  
 Counter++;  
}  

  

also tell me can we change the code in such a way which increase execution speed?

Thanks

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-07-08T15:16:02.353+00:00

    There are no new statements in your code so you cannot switch to the new initializer syntax if that is what you're asking about.

    Your code is actually just in need of some simple refactoring. The most complex aspect is your various logic to figure out FY vs quarter and A vs E and since ultimately it just impacts the output I think you can add a simple RE to capture all this to avoid the string manipulation. Perhaps something like this.

       var lstperiods = periods.Split(',');  
         
       //Guessing at the logic here but it appears your periods are formatted like 2021A or FY2022 in which case we can simplify this logic to parse out the info  
       //Breaking this up from the Split just so you can see the code, can be combined  
       var items = from p in lstperiods  
                   let info = PeriodInfo.Parse(p)  
                   where info != null  
                   select new { Period = p, Info = info };  
         
       //Another issue is that you appear to be using the same cell each time as you're always using [7, Counter] so only the last item really matters...  
       foreach (var item in items)  
       {  
           ws.Cells[7, Counter].Value = $"{(item.Info.IsFiscalYear ? "FY" : "")}{item.Info.Year}{item.Info.Category}";  
       };  
    

    This relies on a helper type to handle the string parsing and I'm just guessing at your string format.

       public class PeriodInfo  
       {  
           public static PeriodInfo? Parse ( string value )  
           {  
               var match = s_regex.Match(value);  
               if (!match.Success)  
                   return null;  
         
               if (!Int32.TryParse(match.Groups["year"].Value, out var year))  
                   return null;  
         
               return new PeriodInfo() {  
                   Year = year,  
                   Category = match.Groups["category"].Value,  
                   Quarter = match.Groups["quarter"].Value  
               };  
           }  
         
           public int? Year { get; set; }  
         
           public string Quarter { get; set; }  
           public bool IsFiscalYear => String.Equals(Quarter, "FY", StringComparison.OrdinalIgnoreCase);  
         
           public string Category { get; set; }  
         
           //Format this RE to fit your format - (A | E)yy(#Q | FY)  
           private static Regex s_regex = new Regex(@"(?<category>A | E)(?<year>\d{2})(?<quarter>\dQ | FY)",   
                               RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);  
       }  
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.