-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtility.cs
66 lines (51 loc) · 1.73 KB
/
Utility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace DataStructuresAndAlgos
{
public static class Utility
{
public static string CollectionToString<T>(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException();
}
if (collection.Count() == 0)
{
return "{ }";
// Avoids awkwardly removing an extra space later
}
var builder = new StringBuilder("{ ");
foreach (var item in collection)
{
builder.Append($"{item}, ");
}
var length = builder.Length;
builder.Remove(length - 2, 2).Append(" }");
return builder.ToString();
}
private static void TestCollectionToString()
{
// Test CollectionToString for
// null
// length == 0
// length == 1
// length == 2(+)
// (Permanently) empty array
// Arrays cannot change size
// Empty array in C# is as close as you can get to an immutable collection
// in C#
// Can use the same instance for all purposes, as you can with String.Empty
var intArray = new int[] { };
Console.WriteLine(CollectionToString(intArray));
intArray = new int[] { 42 };
Console.WriteLine(CollectionToString(intArray));
intArray = new int[] { 7, 11 };
Console.WriteLine(CollectionToString(intArray));
intArray = null;
//Console.WriteLine(CollectionToString(intArray));
}
}
}