I was asked to answer the following question before setting up a phone interview, but they said my code wasn't detailed enough.
Question:
Without using any of the .NET Collection or Linq libraries (i.e. without using List), implement a ListOfStrings object that contains a set of strings. This object has the following methods:
Add(string) - inserts a string to the end of the list ToString() - Returns the list as a comma separated string.Example Usage:
ListOfStrings list = new ListOfStrings(); // set is empty list.Add("abc"); // set is "abc" list.Add("xyz"); // set is now "abc", "xyz" list.Add("123"); // set is now abc", "xyz", "123" list.ToString(); // Should return "abc,xyz,123"
Ideally, this code should be able to handle large numbers of items.
Answer:
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
while (true)
{
ListOfStrings ls = new ListOfStrings();
ls.Add("test1");
ls.Add("test2");
ls.Add("122");
ls.Add("");
ls.ToString();
Console.WriteLine(ls.ToString());
}
}
}
public class ListOfStrings
{
private string ListOfString;
public ListOfStrings()
{
ListOfString = null;
}
public string Add(string input)
{
if (input != string.Empty)
{
ListOfString = ListOfString == null ? input : ListOfString + "," + input;
}
return ListOfString;
}
public string ToString()
{
return ListOfString;
}
}
}
Please let me know feedback on the code.
Add
andToString
are required usingStringBuilder
is simple and efficient. If we really need a collection, the simplest approach would be a doubly linked list. If random access is required we'd need a tree. \$\endgroup\$List<T>
over a linked list as wll. \$\endgroup\$IEnumerable<T>
,ICollection<T>
andIList<T>
, so claiming it's not a collection is dubious IMO. There are also various immutable and readonly collections. The .net parts of MSDN are generally pretty low quality and contain a number of dubious claims like this. \$\endgroup\$