Too often we see developers re-inventing the wheel, so I’d like to try to make a round-up of the common methods people don’t use enough
I’m not saying I’ never made the same mistakes, but I’m going to try to group them to avoid you (and me) to do them again
First example : how to properly join a list of strings (jump to the conclusion if you want the direct answer)
imagine you have a list of strings :
IEnumerable<string> mylist = new[] { "dog", "cat", "turtle", "bird", "fish" };
and as a result you would like
dog, cat, turtle, bird, fish
so joining all items by a comma followed by a blank space
what devs usually do is :
string result = ""; foreach(string item in mylist) // joining all items { result += item + ", "; }
which will result in
dog, cat, turtle, bird, fish,
so they will remove the trailing “, ”
string result = ""; foreach(string item in mylist) // joining all items { result += item + ", "; } result =result.TrimEnd(new char[] { ',', ' ' }); // or result = result.Remove(result.LastIndexOf(", "), 2); // or another method
this will give the wanted “dog, cat, turtle, bird, fish”
Another way to go is
List<string> mylist = new List<string>(new []{ "dog", "cat", "turtle", "bird", "fish" }); string result = ""; for (int i = 0; i < mylist.Count; i++) { if (i != 0) { result += ", "; } result += mylist[i]; }
This will work as well
But there is a method that was there for ever (I mean since the first version of the framework)
This is a static method of the String class: the Join method.
It has several signatures, but basically it takes the separator you want as the first parameter, and a collection of string or object as second parameter.
If you want to see how it’s implemented : check the method in the framework source reference
Conclusion
You can really shorten you code by using this method
string result = String.Join(", ",mylist);
Bonus
Of course you don’t have to limit yourself to a comma as a separator, here is an example to create an html unordered list:
List<string> mylist = new List<string>(new []{ "dog", "cat", "turtle", "bird", "fish" }); // step 1 :create the inner "li" string listItems = string.Join("</li><li>", mylist); // step 2 : complete the first and last "li" and surround by an "ul" string result = string.Format("<ul><li>{0}</li></ul>",listItems);
output :
<ul><li>dog</li><li>cat</li><li>turtle</li><li>bird</li><li>fish</li></ul>
or :
- dog
- cat
- turtle
- bird
- fish
Incoming search terms:
- 1 know net
- intitle: net gaming-addiction