2017-08-30 107 views
3

背景

我從DataGridView我有一些行,我轉換爲實體對象。在轉換過程中,我重置了一些值。由於「基本」數據來自DataBoundItem的當前DataGridViewRow,使用對象初始化程序因此是不是我正在尋找的選項,我不想分配來自第一個對象的每個值(冗餘)。如何在C#中一次分配多個對象屬性?

所以我的問題是:是否有可能一次分配多個對象屬性,如果,你如何實現它?

研究

我發現下面的問題,但他們都不是解決我的問題:

Assigning multiple variables at once in c#

Assign multiple variables at once

Setting multiple properties with one declaration in Windows Forms (C#)

代碼

foreach (DataGridViewRow CurrRow in DataGridView.Rows) 
{ 
    SomeObject SomeObj = (SomeObject) CurrRow.DataBoundItem; 
    SomeObj.PropertyA = 0; 
    SomeObj.PropertyB = 0; 
    SomeObjCollection.Add(SomeObj); 
} 

我已經試過

單獨的與昏迷分配屬性(在昏迷給出了一個語法錯誤):

TimeEntries.Hours, TimeEntries.Expenses = 0; 
+3

multiple =語句有什麼問題? –

回答

4

您可以使用=運算符在鏈中指定它們:

TimeEntries.Hours = TimeEntries.Expenses = 0; 

就好像你會向後讀這句話一樣。

在循環的情況下,它應該是這樣的:

foreach (DataGridViewRow CurrRow in DataGridView.Rows) 
{ 
    SomeObject SomeObj = (SomeObject) CurrRow.DataBoundItem; 
    SomeObj.PropertyA = SomeObj.PropertyB = 0; 
    SomeObjCollection.Add(SomeObj); 
} 

重要提示:

如果你正在處理引用類型這將只分配1引用不同的屬性。所以改變其中一個會影響所有其他屬性!

+0

謝謝!這正是我一直在尋找的! –

+0

@chade_歡迎您在使用此參考類型時注意! 'int'和'double'等將毫無問題地工作,但引用類型的屬性將不再獨立!我補充了一下。 –

+0

它工作在我的情況,所以它似乎我沒有使用引用類型。 –

0

元組的解構:

(TimeEntries.Hours, TimeEntries.Expenses) = (0, 0); 
0

一個解決方案是在每個階段使用新的對象。 而不是設置屬性,產生一個新對象,即LINQ Select。 然後,你可以使用一個Constructor and/or Object Initialization

你可以有2個不同類型的每個階段。

// Using LINQ 
    SomeObjCollection.AddAll(DataGridView.Rows 
     .Select(currRow => new SomeObject(CurrRow.DataBoundItem) 
     { 
       PropertyA = 0; 
       PropertyB = 0; 
     }); 

// Using yield (I'd use LINQ personally as this is reinventing the wheel) 
// But sometimes you want to use yield in your own extension methods 
IEnumerable<SomeObject> RowsToSomeObject() 
{ 
    foreach (var currRow in DataGridView.Rows) 
    { 
     yield new SomeObject(CurrRow.DataBoundItem) 
     { 
       PropertyA = 0; 
       PropertyB = 0; 
     } 
    } 
} 
// and then later in some method: 
SomeObjCollection.AddAll(RowsToSomeObjects()) 

雖然這可能不是在技術上是你問什麼,這是另一種模式則可能是與概念的語言被用於什麼。

我推薦學習map/reduce(Select/Aggregate)成語,因爲它們通常在數據處理上比傳統循環和麪向副作用的代碼更適合用於數據處理,因爲它們會繼續突出顯示同一個對象。

如果此操作是中介,那麼您可以直接使用匿名對象,直到獲得最終返回數據類型。

相關問題