You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.9 KiB
77 lines
2.9 KiB
// Author: Gockner, Simon
|
|
// Created: 2020-02-13
|
|
// Copyright(c) 2020 SimonG. All Rights Reserved.
|
|
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using GBase.Api;
|
|
using GBase.Exceptions;
|
|
|
|
namespace GBase.Helpers
|
|
{
|
|
internal static class Enumerables
|
|
{
|
|
private const char ENUMERABLE_STRING_DIVIDER = ',';
|
|
|
|
/// <summary>
|
|
/// Convert an <see cref="IEnumerable"/> to a GBase <see cref="string"/>
|
|
/// </summary>
|
|
/// <param name="enumerable">The <see cref="IEnumerable"/></param>
|
|
/// <returns></returns>
|
|
public static string ToGBaseString(this IEnumerable enumerable)
|
|
{
|
|
StringBuilder @string = new StringBuilder();
|
|
foreach (var item in enumerable)
|
|
{
|
|
@string.Append($"{item}{ENUMERABLE_STRING_DIVIDER}");
|
|
}
|
|
|
|
char lastChar = @string[^1];
|
|
if (lastChar == ENUMERABLE_STRING_DIVIDER)
|
|
@string.Remove(@string.Length - 1, 1);
|
|
|
|
return @string.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Convert a given <see cref="string"/> to an <see cref="IEnumerable{T}"/> of <see cref="Type"/> <typeparamref name="TEnumerable"/>
|
|
/// </summary>
|
|
/// <typeparam name="TEnumerable">The <see cref="IEnumerable{T}"/> <see cref="Type"/></typeparam>
|
|
/// <param name="string">The given <see cref="string"/></param>
|
|
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="Type"/> <typeparamref name="TEnumerable"/></returns>
|
|
/// <exception cref="InterfaceEnumerablePassedException">Interface was passed to an <see cref="IEnumerable{T}"/></exception>
|
|
public static TEnumerable ConvertToGBaseEnumerable<TEnumerable>(string @string)
|
|
{
|
|
//get generic type parameter of TEnumerable
|
|
Type genericType = typeof(TEnumerable).GetGenericArguments()[0];
|
|
|
|
Type listType = typeof(List<>);
|
|
Type genericList = listType.MakeGenericType(genericType);
|
|
IList enumerable = (IList) Activator.CreateInstance(genericList);
|
|
|
|
foreach (var value in @string.Split(ENUMERABLE_STRING_DIVIDER))
|
|
{
|
|
object item;
|
|
|
|
if (genericType.GetInterfaces().Contains(typeof(IGBaseObject)))
|
|
{
|
|
if (genericType.IsInterface)
|
|
throw new InterfaceEnumerablePassedException(genericType);
|
|
|
|
IGBaseObject gBaseObject = (IGBaseObject) Activator.CreateInstance(genericType);
|
|
gBaseObject.InitializeFromString(value);
|
|
item = gBaseObject;
|
|
}
|
|
else
|
|
item = Convert.ChangeType(value, genericType);
|
|
|
|
enumerable.Add(item);
|
|
}
|
|
|
|
return (TEnumerable) enumerable;
|
|
}
|
|
}
|
|
} |