使用 Linq 选择 emum 的子集(用于绑定 ComboBox

发布于 2024-09-30 20:05:00 字数 456 浏览 0 评论 0原文

我有一个枚举

public enum Positions : byte
{
  Manager = 0,
  CEO = 1, 
  Lawyer =2,
  Intern =3,
  Janitor = 4,
}

是否可以获取这些 emum 的子集以与 WPF 中的 ComboBox 绑定?只说那些枚举值 <=2 和 >= 0?我正在尝试:

var subset = from p in Positions where p <= 2 && p >= 0 select p; 
myComboBox.ItemsSource = subset;

没有成功(位置被标记为错误,并显示“无法找到查询模式的实现...”)

我认为使用 LINQ 会很好,但如果有另一种简单的方法,那就可以了也很有趣。 谢谢, 戴夫

I have an enum

public enum Positions : byte
{
  Manager = 0,
  CEO = 1, 
  Lawyer =2,
  Intern =3,
  Janitor = 4,
}

Is it possible to get a subset of these emums to bind with a ComboBox in WPF? Say only those enum values <=2 and >= 0? I was trying:

var subset = from p in Positions where p <= 2 && p >= 0 select p; 
myComboBox.ItemsSource = subset;

without success (Positions is flagged as error with "Could not find an implementation of the query pattern...")

I was thinking that this would be nice to use LINQ on, but if there's another simple way, that would be interesting too.
Thanks,
Dave

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

左秋 2024-10-07 20:05:00

您需要获取枚举值并将其转换为正确的类型:

var subset = from p in Enum.GetValues(typeof(Positions)).Cast<int>()
             where p <= 2 && p >= 0 select (Positions)p;

You'll need to get the enum values and cast it to the proper type:

var subset = from p in Enum.GetValues(typeof(Positions)).Cast<int>()
             where p <= 2 && p >= 0 select (Positions)p;
凉风有信 2024-10-07 20:05:00

最后的演员是不必要的。

var subset = from p in Enum.GetValues(typeof(Positions)).Cast<Positions>() where p <= Postions.Lawyer && p >= Positions.Manager select p;

The last cast is unnecessary.

var subset = from p in Enum.GetValues(typeof(Positions)).Cast<Positions>() where p <= Postions.Lawyer && p >= Positions.Manager select p;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文