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







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

George Pagotelis said...

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.

Unknown said...

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);

Unknown said...

dear Sir
I have Page1.aspx with DIV
i am calling Page2.aspx with jQuery Load and Loading in DIV
Page2.aspx has Button..when I click on button page1 vanishes please guide