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

lesponce 176 Reputation points
2022-04-21T20:50:06.537+00:00

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
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,164 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
C#
C#
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.
10,245 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-04-22T06:18:27.257+00:00

    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  
                            }).ToList();  
    

    The result like this:

    195359-1.gif


    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,
    Dillion


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,021 Reputation points
    2022-04-21T21:27:29.313+00:00

    that's what regex is for:

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