比较时选择多个枚举值 [英] Selecting Multiple Enum Values when comparing

查看:264
本文介绍了比较时选择多个枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的代码:

  public enum CategoryType {E1,E2,E3,E4} 

List1.Add(new model {Line =Line 1 Category = model.CategoryType.E3 | model.CategoryType.E1});
List1.Add(new model {Line =Line 2,Category = model.CategoryType.E2 | model.CategoryType.E1});
List1.Add(new model {Line =Line 3,Category = model.CategoryType.E4 | model.CategoryType.E3});

var modelEnum = CategoryType.E1 | CategoryType.E3

var ValidLines = List1.Where(P => P.Category == modeEnum).ToList()
.Select(P => P.Line).ToList ();

上述代码无效。由于我正在寻找E1或E3,它应该返回任何包含E1或E3的项目。在这种情况下,它应该返回所有3个项目,因为它们都包含E1或E3。



我做错了什么?



谢谢

解决方案

你似乎有点困惑。我相信你想要的是使用你的枚举的Flags属性,然后为它们分配唯一的值(这很难导致你的代码无效)。例如:

  [Flags] 
public enum CategoryType {E1 = 1,E2 = 2,E3 = E4 = 8}

这样你的位或运算符(|)将允许你正确将您的值(最多31个值,加上0)合并为唯一值。要测试,你想做这样的事情:

  if((value& CategoryType.E2)== CategoryType.E2 ){... 

他们以你的方式拥有,或者返回非唯一的int。你有的是这样的:

  public enum CategoryType {E1 = 0,E2 = 1,E3 = 2,E4 = 3} 

这是默认的枚举行为。所以E1 | E3为0 | 2是2 E3是1 | 2是3,与E4相同。


I am trying to select different type of Enum Values when comparing, based on what user selected.

This is my code:

    public enum CategoryType { E1, E2, E3, E4 }

    List1.Add(new model{ Line = "Line 1", Category = model.CategoryType.E3| model.CategoryType.E1});
    List1.Add(new model{ Line = "Line 2", Category = model.CategoryType.E2 | model.CategoryType.E1});
    List1.Add(new model{ Line = "Line 3", Category = model.CategoryType.E4  | model.CategoryType.E3});

var   modelEnum = CategoryType.E1 | CategoryType.E3

var ValidLines = List1.Where(P => P.Category == modeEnum ).ToList()
                      .Select(P => P.Line).ToList();

The above code does not work. Since I am looking for E1 or E3, it should return ANY items that contains E1 or E3. In this case, it should return all 3 items above because all of them contains either E1 or E3.

What am I doing wrong?

Thanks

解决方案

You seem to be a bit confused. I believe what you want is to use the Flags attribute on your enum then assign unique values to them (it's difficult cause your code is invalid). For example:

[Flags]
public enum CategoryType { E1 = 1, E2 = 2, E3 = 4, E4 = 8 }

In this way your 'bit or' operator (|) will allow you to properly combine your values (up to 31 values, plus 0) into a unique value. To test it you want to do something like this:

if ((value & CategoryType.E2) == CategoryType.E2) { ...

They way you have it your bit or's will return non-unique ints. What you have is this:

public enum CategoryType { E1 = 0, E2 = 1, E3 = 2, E4 = 3 }

This is the default enum behavior. So E1 | E3 is 0 | 2 which is 2. E2 | E3 is 1 | 2 which is 3, which is the same as E4.

这篇关于比较时选择多个枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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