所以我有CardBase抽象类和 我想提取一些随机卡元素排除一些特定的卡列表。 所以我确实喜欢这个。
public List<CardBase> GetRandExclude(List<CardBase> list, int elementsCount, List<CardBase> excludeList)
{
var returnCards = from card in list
where !excludeList.Contains(card)
select card;
foreach (CardBase cd in returnCards.Take(elementsCount))
{
Debug.Log("Selected random card is "+cd.name);
}
return (List<CardBase>) returnCards.Take(elementsCount);
}
我做对了吗? 还有更好的方法吗? 提前致谢。
所以我改变了一点。这似乎有效。
public List<CardBase> GetRandExclude(List<CardBase> list, int elementsCount, List<CardBase> excludeList)
{
var returnCards = from card in list
where !excludeList.Contains(card)
select card;
foreach (CardBase cd in returnCards.OrderBy(arg => Guid.NewGuid()).Take(elementsCount).ToList())
{
Debug.Log("Selected random card is "+cd.name);
}
return returnCards.OrderBy(arg => Guid.NewGuid()).Take(elementsCount).ToList();
}
答案 0 :(得分:1)
您可以使用Linq路线并使用Except
提供CardBase
进行某种形式的相等比较。另外,您可以使用重载并提供IEqualityComparer<CardBase> comparer
从那里你想从剩余的可用卡中随机选择卡片。
static Random randomizer = new Random();
public List<CardBase> GetRandExclude(List<CardBase> list, int elementsCount, List<CardBase> excludeList) {
var availableCards = list.Except(excludeList).ToList();
int count = Math.Min(elementsCount, availableCards.Count);
var selectedCards = new HashSet<CardBase>();
do{
var index = randomizer.Next(0, availableCards.Count);
var card = availableCards[index];
selectedCards.Add(card);
} while (selectedCards.Count < count);
foreach (CardBase cd in selectedCards) {
Debug.Log("Selected random card is " + cd.name);
}
return selectedCards.ToList();
}
答案 1 :(得分:0)
您的代码会出现转换异常。
首先获取cardBase的IEnumerable
。
然后使用ToList()
public List<CardBase> GetRandExclude(List<CardBase> list, int elementsCount, List<CardBase> excludeList)
{
var returnCards = from card in list
where !excludeList.Contains(card)
select card;
foreach (CardBase cd in returnCards.Take(elementsCount))
{
//Debug.Log("Selected random card is " + cd.name);
}
IEnumerable<CardBase> newList = returnCards.Take(elementsCount);
return newList.ToList();
}