我想从包含三个元素的枚举中选择第三个元素,同时知道我已经选择了哪两个元素。比较枚举最有效的方法是什么?
编辑:
到目前为止,我已经提出了以下内容:
Drawable.Row alternateChoice = (Drawable.Row)ExtensionMethods.Extensions.DefaultChoice(new List<int>() { (int)chosenEnum1, (int)chosenEnum2 }, new List<int>() { 0, 1, 2 });
Drawable.Row 是枚举,第一个列表是已经选择的内容,第二个列表包含可能的选择。 DefaultChoice 的定义如下。我知道它具有二次时间复杂度,这就是为什么我要求更好的解决方案:
public static int DefaultChoice(List<int> chosen, List<int> choices)
{
bool found = false;
foreach (int choice in choices)
{
foreach (int chosenInt in chosen)
{
if (chosenInt == choice)
{
found = true;
break;
}
}
if (!found)
{
return choice;
}
found = false;
}
return -1;
}
请您参考如下方法:
试试这个:
List<MyEnum> selectedValues = new List<MyEnum>();
selectedValues.Add(MyEnum.firstValue); // Add selected value
selectedValues.Add(MyEnum.secondValue); // Add selected value
List<MyEnum> valuesLeftOver = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList();
valuesLeftOver = valuesLeftOver.Except(selectedValues).ToList<MyEnum>(); // This will result in the remaining items (third item) being in valuesLeftOver list.
代码简短。
尽量不要太担心效率。如今,优化算法非常强大,您可能会得到相同的汇编代码来执行此操作,而不是尝试手动执行。