我有两个包含不同类型数据的集合,但它们几乎具有相同的字段集合。 在一个函数中,我需要根据一个条件遍历其中一个集合。 我想只编写一个代码块来覆盖这两种情况。 例如: 我有以下代码:
if (condition1)
{
foreach(var type1var in Type1Collection)
{
// Do some code here
type1var.Notes = "note";
type1var.Price = 1;
}
}
else
{
foreach(var type2var in Type2Collection)
{
// the same code logic is used here
type2var.Notes = "note";
type2var.Price = 1;
}
}
现在,我想简化这段代码,只使用相同的逻辑一次(因为它们是相同的),类似于以下内容(附注:我知道以下代码不正确,我只是解释我想要做什么):
var typecollection = Condition1 ? Type1Collection : Type2Collection;
foreach(var typevar in TypeCollection)
{
// the same code logic is used here
typevar.Notes = "note";
typevar.Price = 1;
}
Type1和Type2的定义类似于以下代码(实际上它们是实体对象):
public class Type1 : EntityObject
{
public int Type1ID { get; set; }
public int Type1MasterID { get; set; }
public String Notes { get; set; }
public decimal Price { get; set; }
}
public class Type2 : EntityObject
{
public int Type2ID { get; set; }
public int Type2MasterID { get; set; }
public String Notes { get; set; }
public decimal Price { get; set; }
}
更新1:
我已经包含了一些样本代码,这些代码是我在foreach块内使用的(我正在访问两种类型的公共属性)。
更新2:
我已经包含了Type1和Type2的定义样本,您可以看到这两个类中都有2个公共属性,我希望在foreach块中更新它们。
更新3:
对于混淆造成的困惑,我很抱歉,Type1和Type2都是从EntityObject派生而来的(它们都是我的实体模型的一部分),而Type1Collection和Type2Collection实际上是这两个实体的EntityCollection。