根据不同子类随机排序取前n条记录,数据结构如下:
Id,category,name,template,sub_category,created
记录如下:
1,0,'test1','test','AA','2020-01-01';
1,0,'test2','test2','AA','2020-01-02';
1,0,'test12','test12','BB','2020-01-01';
1,0,'test13','test13','BB','2020-01-01';
1,1,'test21','test21','CC','2020-01-01';
1,1,'test22','test22','CC','2020-01-01';
1,1,'test23','test23','DD','2020-01-01';
每条记录有一个category,每个category对应多个sub_category;
要求按category来确定数据类型,然后根据sub_category来随机后获取前n条记录
如:
category:0
1,0,'test1','test','AA','2020-01-01';
1,0,'test2','test2','AA','2020-01-02';
1,0,'test12','test12','BB','2020-01-01';
1,0,'test13','test13','BB','2020-01-01';
sub_category随机:
1,0,'test2','test2','AA','2020-01-02';
1,0,'test1','test','AA','2020-01-01';
1,0,'test13','test13','BB','2020-01-01';
1,0,'test12','test12','BB','2020-01-01';
若获取前1条记录为:
1,0,'test2','test2','AA','2020-01-02';
1,0,'test13','test13','BB','2020-01-01';
C#代码实现过程:
///从List
public static IDictionary
IDictionary
if (tmpString != null && tmpString.Count > 0)
{
foreach (Items p in tmpString)
{
if (tmpItems.ContainsKey(p.c))
{
IDictionary
if (tmpItem.ContainsKey(p.sc))
{
List
list.Add(p);
tmpItem[p.sc] = list;
}
else
{
List
list.Add(p);
tmpItem.Add(p.sc, list);
}
tmpItems[p.c] = tmpItem;
}
else
{
IDictionary
List
list.Add(p);
tmpItem.Add(p.sc, list);
tmpItems.Add(p.c, tmpItem);
}
}
}
return tmpItems;
}
///从数据字典中获取数据转换成List
///此方法实现了不同子类随机排序取前n条记录
public static List
{
List
if (item != null && item.Count > 0)
{
List
tmpKeys = tmpKeys.OrderBy(s => Guid.NewGuid()).ToList();
int totalCount = 0;
IDictionary
foreach (string kk in tmpKeys)
{
totalCount += item[kk].Count;
tmpTotal.Add(kk, item[kk].Count);
}
int rowCount = 10;
tmpTotal = tmpTotal.OrderBy(o => o.Value).ToDictionary(p => p.Key, o => o.Value);
if (totalCount > rowCount)
{
int subTotal = tmpKeys.Count;
int tmpRowCount = rowCount;
int subCount = subTotal > tmpRowCount ? 1 : tmpRowCount / subTotal;
int remainder = subTotal > tmpRowCount ? 0 : tmpRowCount % subTotal;
for (int i = 0; i < tmpTotal.Count; i++)
{
int tmpCount = subCount;
if (remainder > 0) tmpCount += 1;
var element = tmpTotal.ElementAt(i);
if (subTotal > 0) subTotal--;
if (tmpRowCount > 0) tmpRowCount -= element.Value;
if (element.Value < tmpCount)
{
subCount = subTotal > tmpRowCount ? 1 : tmpRowCount / subTotal;
remainder = subTotal > tmpRowCount ? 0 : tmpRowCount % subTotal;
}
else
{
tmpTotal[element.Key] = tmpCount;
if (remainder > 0) remainder -= 1;
}
}
}
int index = 0;
foreach (string kk in tmpKeys)
{
if (index >= rowCount) break;
List
if (totalCount > rowCount)
{
index += tmpTotal[kk];
tmpItem = item[kk].OrderBy(s => Guid.NewGuid()).Take(tmpTotal[kk]).ToList();
}
else
{
index += 1;
tmpItem = item[kk].OrderBy(s => Guid.NewGuid()).ToList();
}
newString.AddRange(tmpItem);
}
}
return newString;
}