Search code examples
c#listtrim

How to use the trim function to trim inside of a list


I am trying to trim an item called Input (object form .json file) which is inside of a foreach loop.

The code I have at the moment is:

List<string> dhurl = new List<string>();

foreach (JObject item in jArray)
{
    dhurl.Add("https://" + (string)item.SelectToken("Input");
}

input adds "sm-tiktoktrends.com", I want it to only add "tiktoktrends.com", how can I use trim to remove "sm-"?

*To clarify all Input objects will need sm- removed


Solution

  • The question is not clear if all values start with "sm-". If so, and you're willing to use LINQ:

    List<string> dhurl = jArray.Select(item => "https://" + ((string)item.SelectToken("Input")).Substring(3)).ToList();
    

    Otherwise, I might do it something like this:

    List<string> dhurl = jArray
        .Select(item => (string)item.SelectToken("Input"))
        .Select(item => "https://" + (item.StartsWith("sm-") ? item.Substring(3) : item))
        .LoList();
    

    New example based on comment below:

    List<string> dhurl = jArray
        .Select(item =>
            string.Format(
                "https://{0}/?sig={1}",
                ((string)item.SelectToken("Input")).Substring(3),
                (string)item.SelectToken("Signature")
            ))
        .LoList();