Home > Software design >  How to get a substring from a list of items and assign substring value to the same item in C#
How to get a substring from a list of items and assign substring value to the same item in C#

Time:01-06

StartTime AgentId
08/19/2021 07:04:56 AM UTC 33
08/11/2021 02:58:35 PM IST 42
08/12/2021 01:01:51 AM CST 24
08/12/2021 08:52:34 PM UTC 61
public class MyModel
{
  public string  StartTime { get; set; }
  public int      AgentId   { get; set; }
  public string   TimeZone  { get; set; }
  public string   Time      { get; set; }
}

I have the above C# Class model MyModel and its sample data stored as a List<MyModel> in my logic. I need a help to parse the StartTime field of a list such that, the TimeZone field should get the UTC/CST/IST of its corresponding StartTime and Time field of a list should be time stamp from its StartTime i,e: 07:04:56 or 02:58:35 and so on. Finally the list should look like something like below:

StartTime AgentId Time TimeZone
08/19/2021 07:04:56 AM UTC 33 07:04:56 AM UTC
08/11/2021 02:58:35 PM IST 42 02:58:35 PM IST
08/12/2021 01:01:51 AM CST 24 01:01:51 AM CST
08/12/2021 08:52:34 PM UTC 61 08:52:34 PM UTC

CodePudding user response:

Given the fact that all of the segments in your StartTime property have a forced amount of characters thanks to the string format you've chosen (except for the timezone where we could have e.g. CEST but we don't have to worry about that and I'll get to the why in just a second) we can simply use the String.Substring method and for the first parameter, define the character from where the newly to be outputted string should start reading and as the second parameter, the amount of characters it should read from there on out. If we don't set the second parameter the String.Substring method will simply read the string to the very end and since the timezone is the last segment of the StartTime format, the unknown amount of characters for the timezone is no problem for us.

With that in mind, here are some options you can choose from:

If you don't want to adjust your class:

private void ManageMyModels(List<MyModel> models)
{
    models.ForEach(model =>
    {
        model.TimeZone = model.StartTime.Substring(23);
        model.Time = model.StartTime.Substring(11, 11);
    });
}

This solution is pretty simple as it just iterates over every MyModel element and sets the TimeZone and Time property values accordingly to the StartTime value. However, it would be a lot nicer if we didn't always had to do this manually for every model we create so here's a better solution if you don't mind adjusting your class:

public class MyModel
{
    public string StartTime { get; set; }
    public int AgentId { get; set; }
    public string TimeZone => this.StartTime.Substring(23);
    public string Time => this.StartTime.Substring(11, 11);
}

The way this solution works is, whenever you access either the TimeZone or Time property, its assigned code will be executed returning the substring that you need. Performance wise there would be a disadvantage where the code would be executed every time you call either of the properties even when the StartTime value hasn't changed.

Alternatively you could do it the other way around where every time you pass a new value to the StartTime both of the properties would be updated as well:

public class MyModel
{
    private string _startTime;
    public string StartTime
    {
        get => _startTime;
        set
        {
            this._startTime = value;
            this.TimeZone = value.Substring(23);
            this.Time = value.Substring(11, 11);
        }
    }

    public int AgentId { get; set; }
    public string TimeZone { get; private set; }
    public string Time { get; private set; }
}

This eliminates previously mentioned disadvantage but creates a new one where the TimeZone and Time property will always be updated whenever the StartTime property is, even if you wouldn't use it.

Personally, I'd stick to the previous option simply because it's shorter and easier to read.

CodePudding user response:

You can use this sample and run code in this link:

class Program
    {
        static void Main(string[] args)
        {
            var list = new List<string>
            {
                "08/19/2021 07:04:56 AM UTC ",
                "08/11/2021 02:58:35 PM IST ",
                "08/12/2021 01:01:51 AM CST ",
                "08/12/2021 08:52:34 PM UTC "
            };

            var list2 = new List<DateInfo>();
            list.ForEach(e =>
            {
                e = e.Trim();
                var dt = DateTime.Parse(e.Substring(0, e.Length - 3)).Date;
                var tm = DateTime.Parse(e.Substring(0, e.Length - 3)).TimeOfDay;
                list2.Add(new DateInfo
                {
                    StartTime = dt,
                    Time = tm,
                    TimeZone = e[^3..]
                });
            });

            list2.ForEach(e =>
            {
                Console.WriteLine(e.ToString());
            });


        }
    }


    public class DateInfo
    {
        public DateTime StartTime { get; set; }
        public TimeSpan Time { get; set; }
        public string TimeZone { get; set; }

        public override string ToString()
        {
            return ($"StartTime : {StartTime:yyyy/MM/dd}, Time : {Time}, TimeZone : {TimeZone}");
        }

    }
  •  Tags:  
  • Related