Advertisements
Home > ASP.NET > Converting Array or List of data to String => made easy! (C#, MVC3, LINQ)

Converting Array or List of data to String => made easy! (C#, MVC3, LINQ)


Have you needed to convert an Array or any sort of list to a string containing some values which were then divided by, let’s say, commas (“,“)? I think most developers did.

To do that, you could use a For or Foreach cycle, which is probably ugly and takes many lines, especially if you just need to list some names, e.g. “Name1, Name2, … NameN“.

A better and cleaner way is to use some LINQ statement to do that in C#. I will show an example below, and lastly I will show the easier and cleaner way to do so!

/* String Array Example */
var contactArry = new[] {
new {Name = “Rahul”, Id = 1},
new {Name = “Steve”, Id = 2},
new {Name = “Harshil”, Id =3},
new {Name = “Nikunj”, Id = 4},
new {Name = “Kapil”, Id = 5}
};

string strFromArray = contactArry.Aggregate(“”, (a, b) => a + b.Name + “, “);
strFromArray = strFromArray.Remove(strFromArray.LastIndexOf(‘,’)); // Remove Last ‘,’

/* List Of String Example */
List<string> contactList = new List<string>();
contactList.Add(“Rahul”);
contactList.Add(“Steve”);
contactList.Add(“Nikunj”);
contactList.Add(“Harshil”);
contactList.Add(“Graham”);
string strFromList = contactList.Aggregate(“”, (a, b) => a + b + “, “);
strFromList = strFromList.Remove(strFromList.LastIndexOf(‘,’)); // Remove Last ‘,’

###Using string extension built-in into .NET 4.0###

string finalStrFromArray = String.Join(“,”, contactArry.Select(x => x.Name));
string finalStrFormList = String.Join(“,”, contactList.Select(x => x.ToString()));

And that’s it! No need to remove that ugly comma anymore!

Advertisements
Categories: ASP.NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: