Home > Blockchain >  Dynamically extract the name, day and hour from a string[] array like this: JOHN=MO10:00-12:00,TU10:
Dynamically extract the name, day and hour from a string[] array like this: JOHN=MO10:00-12:00,TU10:

Time:12-22

The text file can be like this:

JOHN=MO10:00-12:00,TU10:00-12:00
PETER=TU10:00-12:00,WE10:00-12:00,TH10:00-12:00,FR10:00-12:00
LEE=MO10:00-12:00,TU10:00-12:00,SA10:00-12:00,SU10:00-12:00
LOVELY=TH10:00-12:00,FR10:00-12:00,SA10:00-12:00,SU10:00-12:00

The data will come from a text file with multiple line, the string[] array could be different for each line. I want to extract each line to get the Name, Day, Hour. I want to do is it using C# without any library help.

I got the Name like this:

var employeeNames = employeeName.Split('=')[0];

CodePudding user response:

Split accepts multiple characters

var result = line.Split('=', ',');

If you use that form then you'll get:

result[0]: PETER
result[1]: TU10:00-12:00
result[2]: WE10:00-12:00
result[3]: TH10:00-12:00
result[4]: FR10:00-12:00 

The length of the resulting array will vary, but all elements after 0 can be treated the same: the first two chars define the day, chars 2-7 the start time and 8-13 the end time

foreach(var x in result.Skip(1)){

  var day = x[..2];
  var fromTime = x[2..7];
  var endTime = x[8..13];

  var fromHour = x[2..4];
  var toHour = x[8..10];

}

You can then parse the times to a timespan maybe, use an if or a dictionary to turn the day into a DayOfWeek enum.. (you didn't say what you wanted to do with them)

The "indexing a string using two numbers in brackets" is a feature of more recent c#. If it doesn't work because the project you're doing it in uses a too-old c# version you can use the .Substring(startIndex, length) approach instead

var fromTime = x.Substring(2, 5);

Now we know what you want to do with this info, make a class Person with string Name, double HourlyRate and List<TimeSpan> WorkHours properties. Create a new Person instance on each pass of the loop

Parse your times inside the loop that is extracting the days and name, with var fromTs = TimeSpan.Parse(fromTime) and similar for the toTime

Do var worked = toTs - fromTs; to generate a TimeSpan of eg 8 hours and add it to the WorkHours list

Print a message of the name, and the WorkHours.Sum().TotalHours * HourlyRate

At the end of it you have some code like

for each line in the file
  split the line
  make a new person, set the name, rate

  for each of the days
    extract the from and to times
    parse to TimeSpans
    add the difference between the spans to the work hours list

  print the name and the sum of hours times hourly rate
  • Related