Get LiteDb Collection From CLR Type

This post shows how to resolve a `ILiteCollection<BsonDocument>` from LiteDb using a `System.Type` instance.

If you use LiteDB, you might need to resolve a ILiteCollection<BsonDocument> from a .NET type. Here's how you can do that.

public static class LiteDatabaseExtensions
{
    public static ILiteCollection<BsonDocument> GetCollectionByType(this ILiteDatabase database, Type type)
    {
        if (database == null)
        {
            throw new ArgumentNullException(nameof(database));
        }

        if (type == null)
        {
            throw new ArgumentNullException(nameof(type));
        }

        // We can use the database's built in BsonMapper to get the default collection name for the type.
        // This technique only works for collections that were resolved without custom names.
        // EX: var collection = database.GetCollection<T>();
        var collectionName = database.Mapper.ResolveCollectionName(type);
        var collection = database.GetCollection(collectionName);
        return collection;
    }
}