在Azure表中选择随机记录的有效方法是什么?以下代码返回始终相同的记录。是什么原因?
T entity = new T();
TableQuery<T> query = new TableQuery<T>();
var tableSet = table.ExecuteQuery(query).ToList();
if (tableSet.Count >= 1)
{
return tableSet.First();
}
return null;
答案 0 :(得分:2)
以下代码返回始终相同的记录。是什么原因?
如您所知,Azure表中的记录按字母顺序排序,首先是PartitionKey
,然后是RowKey
,每个PartitionKey
。因为您没有指定任何查询条件,所以表服务将开始从顶部(即第一个分区)获取数据。现在你要求表存储只返回一条记录,它将选择该分区中的第一条记录。这就是为什么你得到相同的记录。
如果要获得随机结果,则必须指定一些查询参数。一种可能的方法是随机指定PartitionKey值。如果表中存在PartitionKey,那么它将返回该分区中的第一条记录。
答案 1 :(得分:-1)
感谢您回答这个问题。我到达了以下解决方案,从出库清单中提取随机记录。
T entity = new T();
TableQuery<T> query = new TableQuery<T>();
var tableSet = table.ExecuteQuery(query).ToList();
Random rnd = new Random();
if (tableSet.Count >= 1)
{
return tableSet.ElementAt(rnd.Next(1, tableSet.Count));
}
return null;