2017-08-30 105 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)成语,因为它们通常在数据处理上比传统循环和面向副作用的代码更适合用于数据处理,因为它们会继续突出显示同一个对象。

如果此操作是中介,那么您可以直接使用匿名对象,直到获得最终返回数据类型。

相关问题