繁体   English   中英

检查组合值

[英]Checking set of values for combination

因此,我使用一组枚举来确定4个插槽的值。 有一个叫无,然后有四个叫火,土,水,空气。 槽的值保存在一个整数字典中,该字典作为索引,而枚举作为值。 我想检查此字典的值,以查看是否存在某些组合。 我不确定如何在不对每种情况进行硬编码的情况下最有效地做到这一点。 我知道如何存储组合,但是我不确定如何有效地对照值进行检查。

这个想法是,如果组合是起火,起火,起火,起火,那么它将引发某个事件/功能。

我对字典有些困惑,因为听起来您只是在使用键来指示序列。 我猜这是SortedDictionary<int, Elements> (尽管可能无关紧要。)但首先:

要比较任何两个列表,可以使用SequenceEquals

假设这是您的枚举:

enum Elements { None, Fire, Earth, Water, Air }

假设您要检查的组合是:

var elementsToMatch = new Elements[] { Elements.Fire, Elements.Fire, Elements.Fire };

您可以这样做:

var matches = dictionary.Values.SequenceEquals(elementsToMatch);

如果两个集合都包含相同顺序的相同元素,则为true,否则为false。

如果顺序并不重要,只需元素的组合,那么您可以首先对它们进行排序:

var matches = dictionary.Values.OrderBy(v=>v)
    .SequenceEquals(elementsToMatch.OrderBy(e=>e));

为此需要Dictionary吗?

您可以这样做:

var elements = new Dictionary<int, Elements>(); // or SortedDictionary
elements.Add(0, Elements.None);
elements.Add(1, Elements.Fire);
// etc.

或者您可以这样做:

var elements = new Elements[] { Elements.None, Elements.Water };

或使用List<Elements>

无论如何,您访问它的方式将完全相同:

elements[0]
elements[1] 
// etc

使用字典,可能会丢失键。 可能有一个elements[0]elements[2]但没有elements[1]

如果字典的唯一原因是为每个元素提供一个位置,则可以使用数组或列表,因为每个元素已经可以通过其位置进行引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM