PIYUSH Itspk
PIYUSH Itspk

Reputation: 13

Delete only First Character in List<String>

Suppose i have List string named List<string> parts with 3 Index [0,1,2] now i want to remove first character of every index how can i do this Input string :

Part[0]=".delhi"
Part[1]=".10.12.12"
Part[2]=".14.14.14"

Output string: Part[0]="delhi" like...

Upvotes: 0

Views: 3196

Answers (4)

SᴇM
SᴇM

Reputation: 7213

You can use LINQ for that:

List<string> result = Part.Select(s => string.IsNullOrEmpty(s) ? s : string.Join("", s.Skip(1))).ToList();

Also you can create an extension method:

public static class MyExtensions
{
    public static string RemoveFirstChar(this string str)
    {
        return  string.IsNullOrEmpty(str) ? str : string.Join("", str.Skip(1));
    }

    //Or in c#6 and above use expression bodied functions
    /*
    public static string RemoveFirstChar(this string str) => 
        string.IsNullOrEmpty(str) ? str : string.Join("", str.Skip(1));
    */
}

and use it:

List<string> result = Part.Select(s => s.RemoveFirstChar()).ToList();

DotNetFiddle Example

Upvotes: 0

SiL3NC3
SiL3NC3

Reputation: 770

Or using a simple for loop:

 for (int i = 0; i < parts.Count; i++)
 {
     parts[i] = parts[i].Substring(1);
 }

Upvotes: 2

Lucifer
Lucifer

Reputation: 1594

You can do is

   List<string> part = new List<string>();
   part.Add(".delhi");
   part.Add(".10.12.12");
   part.Add(".14.14.14");

   List<string> filteredList = part.Select(x => x.Substring(1)).ToList();

Upvotes: 2

user1672994
user1672994

Reputation: 10839

You can use linq to loop through all the elements in the list and use Substring to return the string except first char.

parts = parts.Select(p => (!string.IsNullOrEmpty(p) && p.Length > 1) ? p.Substring(1) : p).ToList();

Check this link for Substring

Upvotes: 6

Related Questions