@ -2,13 +2,20 @@
// Created: 2020-02-13
// Created: 2020-02-13
// Copyright(c) 2020 SimonG. All Rights Reserved.
// Copyright(c) 2020 SimonG. All Rights Reserved.
using System ;
using System.Collections ;
using System.Collections ;
using System.Collections.Generic ;
using System.Linq ;
using System.Text ;
using System.Text ;
using GBase.Api ;
using GBase.Exceptions ;
namespace GBase.Helpers
namespace GBase.Helpers
{
{
internal static class Enumerables
internal static class Enumerables
{
{
private const char ENUMERABLE_STRING_DIVIDER = ',' ;
/// <summary>
/// <summary>
/// Convert an <see cref="IEnumerable"/> to a GBase <see cref="string"/>
/// Convert an <see cref="IEnumerable"/> to a GBase <see cref="string"/>
/// </summary>
/// </summary>
@ -19,14 +26,51 @@ namespace GBase.Helpers
StringBuilder @string = new StringBuilder ( ) ;
StringBuilder @string = new StringBuilder ( ) ;
foreach ( var item in enumerable )
foreach ( var item in enumerable )
{
{
@string . Append ( $"{item}, " ) ;
@string . Append ( $"{item}{ENUMERABLE_STRING_DIVIDER} " ) ;
}
}
char lastChar = @string [ ^ 1 ] ;
char lastChar = @string [ ^ 1 ] ;
if ( lastChar = = ',' )
if ( lastChar = = ENUMERABLE_STRING_DIVIDER )
@string . Remove ( @string . Length - 1 , 1 ) ;
@string . Remove ( @string . Length - 1 , 1 ) ;
return @string . ToString ( ) ;
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>
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 ;
}
}
}
}
}