Share via


How to remove special character set prefix in list using linq

Question

Friday, July 20, 2018 7:30 AM

Hi All, 

Please help me to remove special character set prefix in below string list here. 

i have below list here. 

 List<string> removalPattern = new List<string>();
            removalPattern.Add(@"[__]");
            string studentInfo = "[__] Student Attendance \n[__] Student Lunch Time\n(**) Parents Meeting Date \n[__] Student Play time\n[__] Student Library time, \n(**) Parents Observation \n";
            var StudentList = Regex.Split(studentInfo, "\n").Where(s => s.Contains(removalPattern[0]) && s != string.Empty).ToArray();

in 'StudentList' i am getting each string with "[__]" prefix. i don't need this prefix. please help me to remove this prefix for each string in list.

Thanks,

Chandu

All replies (3)

Friday, July 20, 2018 2:42 PM

To remove an arbitrary character from the front of a string use TrimStart. To remove from the back use TrimEnd. To remove from both use Trim.

var studentList = from s in Regex.Split(...)
                  select s.TrimStart('_');


 

Michael Taylor http://www.michaeltaylorp3.net


Saturday, July 21, 2018 9:31 AM

Using the string.Replace() method might me a bit more straightforward:

string studentInfo = 
    "[__] Student Attendance " + 
    "\n[__] Student Lunch Time" + 
    "\n(**) Parents Meeting Date " +
    "\n[__] Student Play time" +
    "\n[__] Student Library time, " +
    "\n(**) Parents Observation \n";

var StudentList = Regex.Split(studentInfo
                       .Replace("[__]","")
                       .Replace("(**)",""), "\n")
                       .Where(s => !string.IsNullOrEmpty(s));
StudentList.ToList().ForEach(Console.WriteLine);

You can chain together successive calls to the Replace method to perform multiple replacements on the original string. In this case I deleted the "(**)" string, too.

wizend


Monday, July 23, 2018 7:00 AM

Hi Chandu,

Also you can remove the prefix for each item in the student list:

    List<string> removalPattern = new List<string>();
    removalPattern.Add(@"[__]");
    string studentInfo = "[__] Student Attendance \n[__] Student Lunch Time\n(**) Parents Meeting Date \n[__] Student Play time\n[__] Student Library time, \n(**) Parents Observation \n";
    
    var StudentList = Regex.Split(studentInfo, "\n").Where(s => s.Contains(removalPattern[0]) && s != string.Empty).ToArray();

    List<string> MyStudentList = new List<string>();
    foreach (var item in StudentList)
    {
        MyStudentList.Add(item.Remove(0, 4));
    }

Now the MyStudentList is what you want.

Regards,

Stanly

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].