2010-09-01 13 views
3

考慮以下結構:應用實例的一維陣列上的操作在一行中,使用LINQ

internal struct Coordinate 
{ 
    public Double Top { get; set; } 
    public Double Left { get; set; } 
} 

internal struct Dimension 
{ 
    public Double Height { get; set; } 
    public Double Width { get; set; } 
} 

internal struct Property 
{ 
    public Boolean Visible { get; set; } 
    internal String Label { get; set; } 
    public String Value { get; set; } 
    internal Coordinate Position { get; set; } 
    public Dimension Dimensions { get; set; } 
} 

我需要操縱性能的20種左右的情況下。我想這樣做盡可能幹淨...是否可以在一行代碼中對屬性的數組應用多個操作?

我想沿着線的東西:

new [] 
{ 
    InstanceOfProperty, 
    InstanceOfProperty, 
    InstanceOfProperty ... 
}.Each(p => p.Dimensions.Height = 100.0); 

回答

0

我落得這樣做:

new List<Property> { InstanceOfProperty, InstanceOfProperty, ... }.ForEach((p => 
{ 
    p.Dimensions.Height = 0.0; 
})); 


注:我已經轉換結構爲類。如果我使用原始的基於結構的設計;爲了改變它們的價值,我將不得不「新建」這些結構。像這樣:

new List<Property> { InstanceOfProperty, InstanceOfProperty, ... }.ForEach((p => 
{ 
    p.Dimensions = new Dimension { Height = 0.0 }; 
})); 
+0

使用類而不是結構,它應該工作正常 – 2010-09-01 13:18:35

1

如果你寫你自己的Each方法服用Action<T>代表,你可以。

編輯:

實際上它不會工作。您正在使用值類型。任何理由爲什麼它不能class

DimensionProperty都必須是該分配的參考類型,以便在處理該列表後反映出來。

1

您可以編寫一個Each擴展方法,但由於您的對象是結構體,因此無法使其在IEnumerable<T>上工作。然而,你可以使陣列上的工作原理,使用委託與ref參數的擴展方法:

public static class ExtensionMethods 
{ 
    public delegate void RefAction<T>(ref T arg); 

    public static void Each<T>(this T[] array, RefAction<T> action) 
    { 
     for(int i = 0; i < array.Length; i++) 
     { 
      action(ref array[i]); 
     } 
    } 
} 

... 

new [] 
{ 
    InstanceOfProperty, 
    InstanceOfProperty, 
    InstanceOfProperty ... 
}.Each((ref Property p) => p.Dimensions.Height = 100.0); 

但是,由於Dimension也是一個結構,它不會以這種方式工作(和編譯器將檢測並給你一個錯誤)。你必須做這樣的事情,而不是:

new [] 
{ 
    InstanceOfProperty, 
    InstanceOfProperty, 
    InstanceOfProperty ... 
}.Each((ref Property p) => p.Dimensions = new Dimension 
          { 
           Width = p.Dimensions.Width, 
           Height = 100.0 
          }); 

就整體而言,一切都將是如果你的類型爲類,而不是結構很多簡單...

+0

看起來整潔。這將是我的第二次「嘗試」。謝謝。你能否檢查我對這個問題的回答,並告訴我你是否預見到任何問題? – roosteronacid 2010-09-01 12:20:42