tags:

views:

83

answers:

1

Does anyone know how to select random objects from a Db4o db?

+1  A: 

Hi, I think the best way is this. Run a query and get the result as IList. Since the returned list lazy-loads the object (at least in embedded-mode) you can pick random objects by the index.

Something like this:

    public static ICollection<T> RandomObjects<T>(IList<T> objectSet, int amount)
    {
        var resultSet = new HashSet<T>();
        var random = new Random();
        amount = Math.Min(objectSet.Count, amount);
        while (resultSet.Count<amount)
        {
            resultSet.Add(objectSet[random.Next(amount)]);
        }
        return resultSet;
    }

And then use it:

    IList<Person> potentialObjects = container.query(Person.class);
    ICollection<Person> randomObject = RandomObjects(potentialObjects,10);

Another possibility would be to build a LINQ-Query which randomly matches. However such a query cannot be optimized, so could perform badly.

var random = from Person p in dbc
          where new Random().Next(2) == 1 
          select p;

Edit: Changed to C#

Gamlor