jQuery and ASP.NET

May 1, 2009

Quickly Replace Data in a String Array using LINQ




LINQ is amazingly flexible. Recently, I came across a client requirement where the client wanted to replace all '@' characters in emails with the text [attherate]. Here's how it can be done easily using LINQ. The same can also be done by looping through the array and replacing it, but LINQ gives you a lot of flexibility in filtering the data.

C#


        string[] emails = { "Shakiy@gmail.com", "Mary@hotmail.com", "Glenn@gmail.com", "Hillock@yahoo.com"};


 


        var modEmail = from em in emails


                           select new


                           {


                               EmailID = em,


                               ModifiedEmail = Regex.Replace(em, "[@]", "[attherate]")


                           };


 


        foreach (var mo in modEmail)


        {


            Response.Write(mo.ToString() + "<br/>");


        }




VB.NET


Private emails() As String = {"Shakiy@gmail.com", "Mary@hotmail.com", "Glenn@gmail.com", "Hillock@yahoo.com"}


 


var modEmail = from em in emails ReadOnly Property [New]() As select


                       em, ModifiedEmail = Regex.Replace(em, "[@]", "[attherate]")


                       EmailID = em, ModifiedEmail


End Property


 


For Each mo In modEmail


    Response.Write(mo.ToString() & "<br/>")


Next mo




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Quickly Replace Data in a String Array using LINQ"
  1. George said...
    January 14, 2010 4:12 PM

    Do you have a find and replace or is that still done in the select query part.

    e.g. I have a datarow in DataTable (or string) but I want to replace "<" to "<" & ">" to ">", etc.

    thanks,

    George.

  2. sid said...
    November 8, 2010 3:25 AM

    string[] emails = { "Shakiy@gmail.com", "Mary@hotmail.com", "Glenn@gmail.com", "Hillock@yahoo.com" };
    var newmodEmail = emails.Select(x => new { EmailID = x, ModifiedEmail = Regex.Replace(x, "[@]", "[attherate]") });
    Array.ForEach(newmodEmail.ToArray(), Console.WriteLine);

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions