如何使用C#从列表中挑选随机对象? [英] How can I pick random objects out of a list with C#?

查看:124
本文介绍了如何使用C#从列表中挑选随机对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IQueryable,其中包含300多个对象:

I have an IQueryable containing more than 300 objects:

public class Detail
{
    public int Id { get; set; }
    public int CityId { get; set; }
    public bool Chosen { get; set; }
}

IQueryable<Detail> details = ...

我该如何反对随机选择50个对象?我假设我需要使用.ToList()进行转换,但是我不确定如何挑选随机元素.

How can I go against this an at random pick out 50 objects? I assume that I would need to convert this with .ToList() but I am not sure how I could pick out random elements.

推荐答案

300不是很多,所以可以,将其列为列表:

300 is not very much, so Yes, make it a List:

IQueryable<Detail> details = ...
IList<Detail> detailList = details.ToList();

现在您可以选择一个随机项目:

And now you can pick a random item :

var randomItem = detailList[rand.Next(detailList.Count)];

,您可以重复50次.但是,这将导致重复,并且消除它们的过程将变得混乱.

and you could repeat that 50 times. That would however lead to duplicates, and the process to eliminate them would become messy.

因此,请使用标准随机播放算法,然后选择前50个:

So use a standard shuffle algorithm and then pick the first 50 :

Shuffle(detailList);
var selection = detailList.Take(50);

这篇关于如何使用C#从列表中挑选随机对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆