We can use reflexion and Linq.
using System.Reflection;
using System.Linq;
Having this dedicated class to store the arrays by default, as well as initialize a complete list of possible elements, and offer a method to obtain a slice, i.e. a list made up of the first n-elements:
static class DefaultArrays
{
static public string[] NodeCassette0 = { "03", "08" };
static public string[] NodeCassette1 = { "04", "09" };
static public string[] NodeCassette2 = { "05", "10" };
static public string[] NodeCassette3 = { "06", "11" };
static public string[] NodeCassette4 = { "07", "12" };
static public List<string[]> All { get; private set; }
static public List<string[]> Take(int count)
{
return All.Take(count).ToList();
}
static public void Initialize()
{
All = typeof(DefaultArrays).GetFields()
.Where(field => field.FieldType == typeof(string[]))
.OrderBy(field => field.Name.Length)
.ThenBy(field => field.Name)
.Select(field => (string[])field.GetValue(null))
.ToList();
}
static DefaultArrays()
{
Initialize();
}
}
The Initialize
method is created this way to possibly allow updating of the entire list in case the arrays are modified at runtime, otherwise the code can be placed directly in the constructor and all arrays marked readonly
.
Here is the algorithm for All
:
- We get all fields of the static class by its type name.
- We filter to select only those being of type array of string.
- We order by the fields name string length.
- Then by this name, thus we finally get for example 1, 2, 30, 40 from 40, 30, 2, 1.
- We do a projection to get the reference of the value instead of the field name using it.
- And we transform the Linq query into a
List<string>
object instance to return.
It uses a pseudo-natural numeric sort assuming all arrays are named:
"[same_same][number_without_trailing_left_0]"
Else we can use a custom comparer:
How do I sort strings alphabetically while accounting for value when a string is numeric?
sort string-numbers
Test
var slice = DefaultArrays.Take(3);
string msg = string.Join(Environment.NewLine, slice.Select(item => string.Join(", ", item)));
Console.WriteLine(msg);
Output
03, 08
04, 09
05, 10
Warning
The slice contains a list of references toward original arrays, thus any modification of a cell of an array in this list will be reflected in the matching array in the static class.
Else we need to copy the arrays with Array.Copy
instead of using Linq.Take
:
static public List<string[]> TakeCopy(int count)
{
var list = new List<string[]>();
foreach ( int index in Enumerable.Range(0, Math.Min(count, All.Count)))
{
int length = All[index].Length;
var array = new string[length];
Array.Copy(All[index], array, length);
list.Add(array);
}
return list;
}