Reputation: 13
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
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();
Upvotes: 0
Reputation: 770
Or using a simple for loop:
for (int i = 0; i < parts.Count; i++)
{
parts[i] = parts[i].Substring(1);
}
Upvotes: 2
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
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