using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace BotSharp.Algorithm.Bayesian
{
internal static class LinqExtensions
{
///
/// Converts an enumerable to a collection
///
///
/// The enumerable.
/// ICollection<T>.
public static ICollection ToCollection(this IEnumerable enumerable)
{
var type = enumerable.GetType();
if (type.IsGenericCollectionType()) return (ICollection)enumerable;
var collection = new Collection();
foreach (var t in enumerable)
{
collection.Add(t);
}
return collection;
}
///
/// Forces evaluation of the enumerable
///
///
/// The enumerable.
public static void Run(this IEnumerable enumerable)
{
var type = enumerable.GetType();
if (type.IsGenericCollectionType()) return;
foreach (var item in enumerable)
{
}
}
///
/// The cache for
///
private static readonly ConcurrentDictionary IsGenericCollectionTypeCache = new ConcurrentDictionary();
///
/// Determines whether the specified type is a (generic) collection.
///
/// The type.
/// true if the specified type is collection; otherwise, false.
public static bool IsGenericCollectionType(this Type type)
{
return IsGenericCollectionTypeCache.GetOrAdd(type, t => type.GetInterfaces()
.Any(ti => ti.IsGenericType
&&
ti.GetGenericTypeDefinition() ==
typeof (ICollection<>)));
}
}
}