2010-09-02 108 views
8

我有一個類是IEnumerable<T>我想擁有不同的屬性,提供過濾IEnumerable<T>訪問。是否有可能擁有一個屬性爲IEnumerable <T>?

因此,例如:

class Shape 
    ShapeType = Box/Sphere/Pyramid 

class ShapeCollection : IEnumerable<Shape> 
{ 
    public IEnumerable<Shape> OnlyBox 
    { 
     foreach(var s in this) 
     { 
      if (s.ShapeType == Box) 
       yield return s; 
     } 
    } 
} 

這是應該如何?只是不確定,關於它完全。

謝謝。

回答

11

當然,但你可能要重寫它作爲

public IEnumerable<Shape> OnlyBox 
{ 
    get { return this.Where(x => x.ShapeType == ShapeType.Box); } 
} 

這不完全一樣的事情。

+0

+1表現力。 – Cumbayah 2010-09-02 18:58:30

+0

謝謝,是的,這在我的腦海裏有點片面。現在我可以清楚地看到它。 – 2010-09-02 19:01:56

+0

WTG w/LINQ FTW。 – Randolpho 2010-09-02 21:20:52

2

當然,即使@ mquander的解決方案可能會更優雅一些,這應該可行(據我所見)。

1

這是有效的,但我認爲是多餘的。如果要公開形狀的強類型列表:

public class Shape 
{ 

} 

public class SomethingThatHasShapes 
{ 
    public List<Shape> Shapes { get; set; } 
    public Boxes 
    { 
     get { return Shapes.Where(s => s.ShapeType = ShapeType.Box); } 
    } 


} 

List<T>類實現IEnumerable。

+0

這樣做的缺點是它會將您的列表暴露給外部影響。 – 2010-09-02 18:59:36

+0

您的第二個屬性需要返回類型。 – 2010-09-02 19:14:55

4
class ShapeCollection : IEnumerable<Shape> 
{ 
    public IEnumerable<Shape> OnlyBoxes 
    { 
     get { return this.Where(s => s.ShapeType == Box); } 
    } 
} 

您錯過了get /括號使其成爲方法。另外什麼是Box,你的意思是ShapeType.Box?也可能將其重命名爲OnlyBoxes,似乎更具描述性。

+0

沒有人給我投票,我的名聲就是這樣。 – 2010-09-02 19:08:07

+0

謝謝我投票給你。我寫了這樣的代碼,因爲我沒有使用VS,也不想寫所有的東西。 – 2010-09-02 19:15:30

1

我個人認爲你的OnlyBox屬性是多餘的。因爲你的類的用戶總是可以選擇像下面那樣使用Linq來獲得相同的性能。所以,除非你可以做到這一點比LINQ的方法比較好,我覺得這是很好離開它的類象的用戶:

var filtered = shapeCol.Where(s => s.ShapeType == Box); 

但是,如果你想要的,而不是一個性質,:

foreach(var s in this) 
{ 
    if (s.ShapeType == Box) 
     yield return s; 
} 

你可以寫:

return this.Where(s => s.ShapeType == Box); 
+0

謝謝,這個想法是因爲這是簡化的,但實際上過濾代碼是非常醜陋的,因爲這是一個非託管類的包裝。所以想讓它對用戶和我自己來說更高一點。 – 2010-09-02 19:03:20

1

喜歡時尚更LINQ會提供你收集的方法:

public IEnumerable<Shape> Boxes() 
{ 
    return this.Where(ss => ss.ShapeType == ShapeType.Box); 
} 

或者只是有用戶做一個Where子句:

// gather boxes 
var query = from shape in shapes 
      where shape.ShapeType == ShapeType.Box 
      select shape; 

否則,沒有錯的IEnumerable作爲一個屬性(記住性質應該是如此簡單,他們很少會拋出異常)。

0

是的。你有什麼是好的。如果你喜歡它的表現力,你可以轉換爲基於lambda的,雖然lambda版本可能有時性能較差(不是那麼多,我會改變lambda版本爲2.0的風格,除非它證明有問題,但足夠,我wouldn除非它使lot更具表現力),否則將不會改變完美的2.0風格。

相關問題