[英]C# how do I implement inheritance using linq?
我有两个基于同一班级的名单。 我希望一个列表继承另一个列表的类属性的值。
class feature {
Guid id;
string featureName;
string featureType;
.....
}
List <feature> companyFeatures;
List <feature> divisionFeatures;
功能列表是在公司级别设置的。
创建部门后,部门应继承公司功能列表中的所有功能。 (不复制)
如果部门在特定功能中的属性值与公司的属性值不同,则用户希望将该属性的值“保存”在部门的功能列表中。
这使用户可以在以后在公司级别添加功能,并在部门级别查看这些新功能。
通常,部门清单中不会有很多项目,因为它们与公司列表相同。
我试图使用linq(外部联接)加入两个列表。 当在分区级别没有列表元素的条目时,它似乎失败。
我想我做错了什么(我可能无法正确理解外部联接),我们将不胜感激。
顺便说一下,有一种建议用于实现继承的设计模式。
开心并度过美好的一天
================================================== =============================
添加示例(希望这可以澄清我的目标)
List <feature> companyFeatures = new List <feature>
{
new <feature> { Guid1 , "Color" , "Text" , .... },
new <feature> { Guid2 , "address" , "Link" , .... },
new <feature> { Guid3 , "logo" , "Picture" , .... }
}
List <feature> divisionFeatures = new List <feature>
{
new <feature> { Guid2 , "address" , "text" , .... },
}
在“继承”之后我要寻找的功能列表应该是:
{
{Guid1, "Color" , "Text" , ...},
{Guid2, "address" , "text" , ...},
{Guid3, "logo" , "Picture" , ...}
}
注意,Guid2现在具有type属性的text值。 希望这可以澄清。
从技术上讲,这不是继承-
如果此处的目标是返回companyFeatures
和divisionFeatures
列表中所有功能的集合,则可以执行以下操作:
IEnumerable<feature> totalFeatures = companyFeatures.Concat(divisionFeatures);
Enumerable.Concat方法将返回IEnumerable<T>
,其中包含两个列表中的元素。
如果我误会了,请纠正我。 您有一个Company
类和一个Division
类,并且它们都有一个List<Feature>
字段? 就像是...
public class Company {
// ...
public List<Feature> CompanyFeatures;
// ...
}
public class Division {
public Company Company; // The company to which the division belongs
// ...
public List<Feature> DivisionFeatures;
// ...
}
如果是这种情况,那么我建议将功能列表转换为只读属性,并使其自动处理“继承”。 例如...
public class Division {
public Company Company; // The company to which the division belongs
// ...
private List<Feature> _divisionFeatures; // private now
public IEnumerable<Feature> DivisionFeatures {
get {
// Take all the features for the divison...
return _divisionFeatures.Concat(
// ... and add all the company features except for those that
// have the same name as one of the division features.
Company.CompanyFeatures.Where(cf => !_divisionFeatures
.Any(df => df.Name == cf.Name))
);
}
}
// ...
}
另外,当然,您仍然可以将List<Feature>
设为公开(以便仍然可以从外部进行操作),并调用该属性,例如DivisionFeaturesWithInheritance
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.