是否有更简洁的方法来做一个等同的IN(aa,bb,cc)?

时间:2010-11-03 20:34:41

标签: c# linq

任何人都知道是否有更清洁/更简单的方法来做同等的事情?

另外,我应该注意哪些副作用?

var setters = from setterBase in Style.Setters
              let setter = (setterBase as Setter)
              let properties = new []{ HorizontalContentAlignmentProperty, VerticalContentAlignmentProperty }
              where setter!=null && properties.Contains(setter.Property)
              select setterBase;

到目前为止,我提出了最好的......

3 个答案:

答案 0 :(得分:1)

没有必要为每个setter新建一个数组。

var properties = new []{
  HorizontalContentAlignmentProperty,
  VerticalContentAlignmentProperty };

var setters = from setter in Style.Setters.OfType<Setter>() 
              where properties.Contains(setter.Property) 
              select setter;

答案 1 :(得分:0)

不是真的。对于两个选项,使用or可能更具可读性,您可以使用OfType代替as - 演员和第一letOfType不会返回null个元素,因此您也可以删除该过滤器:

var setters = from setter in Style.Setters.OfType<Setter>()
              where (setter.Property == HorizontalContentAlignmentProperty ||
                     setter.Property == VerticalContentAlignmentProperty)
              select setter;

答案 2 :(得分:0)

我会这样做。我仍然喜欢在数组中使用属性来轻松支持更多属性。尼斯!

var setters = from setter in Style.Setters.OfType<Setter>()
              let properties = new []{ HorizontalContentAlignmentProperty, VerticalContentAlignmentProperty }
              where properties.Contains(setter.Property)
              select setter;