开发者

Db4o select random objects

Does anyone know how to select random objects from a Db4o开发者_Python百科 db?


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#

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜