使用linq合并三个列表

时间:2016-08-24 21:37:48

标签: c# linq list

我有三个班级 -

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提供了TypeSubType之间的映射。

我有每个班级的列表 - List<Type>List<SubType>List<Association>

我想将它们全部合并到另一个中 - List<TypeInfo>. TypeIdSubTypeId来自AssoicationTypeName来自TypeSubTypeName来自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是否有一种简单的方法?

2 个答案:

答案 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();