简体   繁体   English

db4o选择随机对象

[英]Db4o select random objects

有谁知道如何从Db4o数据库中选择随机对象?

I think the best way is this. 我认为最好的方法是这样。 Run a query and get the result as IList. 运行查询并以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. 另一种可能性是建立一个随机匹配的LINQ查询。 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# 编辑:更改为C#

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM