正确使用LINQ洗牌 [英] Correctly using LINQ to shuffle a deck

查看:72
本文介绍了正确使用LINQ洗牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的纸牌游戏.为了提出一个好的改组算法,我遇到了Jeff Atwood关于编码恐怖的 post

I am attempting to write a simple card game. In an effort to come up with a good shuffling algorithm I came across Jeff Atwood's post on Coding Horror.

但是,当我在调用构造函数后查看对象的内容时,它们并没有被随机播放.

However When I view the contents of the object after calling the Constructor they are not shuffled.

这是我尝试使用Jeff解决方案的方法:

Here is my attempt to use Jeff's Solution:

class MainDeck : List<Card>
{
   public MainDeck()
    {
        this.Add(new Card(1, "Hearts"));
        this.Add(new Card(2, "Hearts"));
        this.Add(new Card(3, "Hearts"));
        ...

        this.OrderBy(a => Guid.NewGuid());
    }
}

这是卡的代码:

class Card
    {
        string suit;
        int value;

        public Card(int value, string suit)
        {
            this.value = value;
            this.suit = suit;
        }

        bool isFaceCard()
        {
            if (value >= 11 || value == 1)
                return true;
            else
                return false;
        }

        public override string ToString()
        {
            return (value +", " + suit);
        }
    }

我应该改变些什么才能使改组工作正常?

What should I change to make the shuffling work?

推荐答案

LINQ方法不会更改现有集合.因此,该语句完全不执行任何操作:this.OrderBy(a => Guid.NewGuid()); 另外,我很确定您不能将其分配给this,因此您不必要么继承自List<T>(这很好),要么要做类似的事情:

LINQ methods are not mutating existing collections. So this statement does nothing at all: this.OrderBy(a => Guid.NewGuid()); Also, I'm pretty sure you can't assign to this, so you have to either don't inherit from List<T> (which is good), or do something like this:

var sorted = this.OrderBy(a => Guid.NewGuid()).ToList();
this.Clear();
this.AddRange(sorted);

也请参见 SO答案,还有更正确的改组算法.

Also look at this SO answer, there is more correct shuffling algorithm.

这篇关于正确使用LINQ洗牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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