如何从 C# 中的列表或 var 中获取随机数量的详细信息
how to get random amount of details from a list or var in c#
我正在从本地 project.it 中的 json 文件读取结果 returns 超过 4000 result.I 只想获得随机数量的结果(介于 500 - 1000) 来自该结果。
var finalResultz = finalResults("All","All","All");//step one
这里returns 4000多条results.then 我把这个列成这样
List<Results> searchOne = new List<Results>();//step two
foreach(var itms in finalResultz)
{
searchOne.Add(new Results
{
resultDestination = returnRegionName(itms.areaDestination),
mainImageurl = itms.testingImageUrl
});
}
ViewBag.requested = searchOne;
但我只想得到像我 said.I 想在第一步或 two.how 中调整计数大小的结果 that.hope 你能帮忙吗?
您可以使用Random
class and Take()
方法提取N个元素。
// create new instance of random class
Random rnd = new Random();
// get number of elements that will be retrieved from 500 to 1000
var elementsCount = rnd.Next(500, 1000);
// order source collection by random numbers and then take N elements:
var searchOne = finalResultz.OrderBy(x => rnd.Next()).Take(elementsCount);
如果您想要随机计算结果,您可以 .Take()
随机记录。首先,您需要 Random
:
var random = new Random();
如果您想要 500-1000 之间,只需获取该范围内的随机值:
var count = random.Next(500, 1001);
然后你可以从集合中取出那些记录:
var newList = oldList.Take(count).ToList();
(当然,您可能要先确保包含那么多条记录。)
请注意,这将从集合中获取 前 N 条记录。因此,为了从集合中的 任意位置 获取随机记录,您需要在获取记录之前对集合进行洗牌(随机化)。有多种方法可以做到这一点。一种可能不是绝对最快但通常 "fast enough" 为简单起见的方法是仅按 GUID 排序。所以像这样:
var newList = oldList.OrderBy(x => Guid.NewGuid()).Take(count).ToList();
或者再次使用随机发生器:
var newList = oldList.OrderBy(x => random.Next()).Take(count).ToList();
我正在从本地 project.it 中的 json 文件读取结果 returns 超过 4000 result.I 只想获得随机数量的结果(介于 500 - 1000) 来自该结果。
var finalResultz = finalResults("All","All","All");//step one
这里returns 4000多条results.then 我把这个列成这样
List<Results> searchOne = new List<Results>();//step two
foreach(var itms in finalResultz)
{
searchOne.Add(new Results
{
resultDestination = returnRegionName(itms.areaDestination),
mainImageurl = itms.testingImageUrl
});
}
ViewBag.requested = searchOne;
但我只想得到像我 said.I 想在第一步或 two.how 中调整计数大小的结果 that.hope 你能帮忙吗?
您可以使用Random
class and Take()
方法提取N个元素。
// create new instance of random class
Random rnd = new Random();
// get number of elements that will be retrieved from 500 to 1000
var elementsCount = rnd.Next(500, 1000);
// order source collection by random numbers and then take N elements:
var searchOne = finalResultz.OrderBy(x => rnd.Next()).Take(elementsCount);
如果您想要随机计算结果,您可以 .Take()
随机记录。首先,您需要 Random
:
var random = new Random();
如果您想要 500-1000 之间,只需获取该范围内的随机值:
var count = random.Next(500, 1001);
然后你可以从集合中取出那些记录:
var newList = oldList.Take(count).ToList();
(当然,您可能要先确保包含那么多条记录。)
请注意,这将从集合中获取 前 N 条记录。因此,为了从集合中的 任意位置 获取随机记录,您需要在获取记录之前对集合进行洗牌(随机化)。有多种方法可以做到这一点。一种可能不是绝对最快但通常 "fast enough" 为简单起见的方法是仅按 GUID 排序。所以像这样:
var newList = oldList.OrderBy(x => Guid.NewGuid()).Take(count).ToList();
或者再次使用随机发生器:
var newList = oldList.OrderBy(x => random.Next()).Take(count).ToList();