0

I have three classes -

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;}
}

The Association gives the mapping between Type and SubType.

I have lists of each class - List<Type>, List<SubType>, List<Association>.

I want to merge them all into another like this - List<TypeInfo>. The TypeId and SubTypeId coming from the Assoication, the TypeName coming from Type and the SubTypeName coming from SubType.

public class TypeInfo 
{
   public int TypeId {get;set;}
   public string TypeName {get;set;}
   public int SubTypeId {get;set;}
   public string SubTypeName {get;set;}
}

Is there an easy way with linq?

2 Answers 2

2

It's very straight forward:

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that did it!
-1

Assuming types and subTypes are of type List and List respectively.

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

1 Comment

Enigmativity answer is better as it uses join. Edited to use expression chain syntax as an alternative to query syntax for the join.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.