How do I Remove Specific Character from a Field in a C# List?

lesponce 156 Reputation points

I got a C# List that it's the result of a LINQ query. I had no issues removing zero records like this.

myList.RemoveAll(x => x.Amount ==0);

How do I remove character "TH" from a column in myList?

Data example: "48 Street" and "48th Street"
I need to remove "th" from records set to "48th Street" so I can have all of them set to "48 Street"

How can I accomplish this in myList?

.NET Standard
.NET Standard
A formal specification of .NET APIs that are available on multiple .NET implementations.
505 questions
A set of technologies in the .NET Framework for building web applications and XML web services.
3,153 questions
A set of technologies in the .NET Framework for building web applications and XML web services.
1,481 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,199 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 24,316 Reputation points Microsoft Vendor

    Hi @lesponce ,

    Agree with Bruce, Regex.Replace method is a good choice. You could refer the following code:

        //Test data  
        var orderlist = new List<Order>()  
            new Order() {Id=1, Address="48 Street", Account=12},  
            new Order() {Id=2, Address="48 Street", Account=0},  
            new Order() {Id=3, Address="48th Street", Account=11},  
            new Order() {Id=4, Address="48 Street", Account=0},  
            new Order() {Id=5, Address="51th Street", Account=15},  
        //var orderresult = orderlist.RemoveAll(c => c.Account == 0);  
        var orderresult2 = orderlist.Where(c => c.Account != 0) //filter data and remove the Account is 0  
                            .Select(c => new Order() {  
                                Id = c.Id,  
                                 Address = Regex.Replace(c.Address, @"(\w+)(\d+)(th)(\s\w+)", "$1$2$4", RegexOptions.IgnoreCase),  
                                  Account = c.Account  

    The result like this:


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

1 additional answer

Sort by: Most helpful
  1. Bruce ( 36,181 Reputation points

    that's what regex is for:

    var clean = Regex.Replace("128th street, "(\\W*)(\\d+)\\W*(th)(\\W+)", "$1$2$4", RegexOptions.IgnoreCase);