我有三个班级 -
public class Type
{
public int TypeId {get;set;}
public string TypeName {get;set;}
}
public class SubType
{
public int SubTypeId {get;set;}
public string SubTypeName {get;set;}
}
public class Association
{
public int TypeId {get;set;}
public int SubTypeId {get;set;}
}
Association
提供了Type
和SubType
之间的映射。
我有每个班级的列表 - List<Type>
,List<SubType>
,List<Association>
。
我想将它们全部合并到另一个中 - List<TypeInfo>.
TypeId
和SubTypeId
来自Assoication
,TypeName
来自Type
,SubTypeName
来自SubType
。< / p>
public class TypeInfo
{
public int TypeId {get;set;}
public string TypeName {get;set;}
public int SubTypeId {get;set;}
public string SubTypeName {get;set;}
}
linq
是否有一种简单的方法?
答案 0 :(得分:2)
非常直接:
List<Type> types = ...
List<SubType> subTypes = ...
List<Association> associations = ...
IEnumerable<TypeInfo> query =
from type in types
join association in associations on type.TypeId equals association.TypeId
join subType in subTypes on association.SubTypeId equals subType.SubTypeId
select new TypeInfo()
{
TypeId = association.TypeId,
SubTypeId = association.SubTypeId,
TypeName = type.TypeName,
SubTypeName = subType.SubTypeName,
};
List<TypeInfo> typeInfos = query.ToList();
答案 1 :(得分:-1)
假设类型和子类型分别是List和List类型。
var associations = new List<Association>();
var typeInfoes = associations
.Join(types, a => a.TypeId, t => t.TypeId,
(a, t) => new TypeInfo
{
TypeId = a.TypeId,
TypeName = t.TypeName,
SubTypeId = a.SubTypeId,
SubTypeName = ""
}
)
.Join(subTypes, ti => ti.SubTypeId, st => st.SubTypeId,
(ti, st) => new TypeInfo
{
TypeId = ti.TypeId,
TypeName = ti.TypeName,
SubTypeId = ti.SubTypeId,
SubTypeName = st.SubTypeName
}
)
.ToList();