2
public class A
{
    public string Value1 { get; set; }
    public int Value2 { get; set; }
    public List<B> Values { get; set; }
    public int Value3 { get; set; }          
}

public class B
{
    public int Id { get; set; }
    public string X { get; set; }
}

public class Result
{
    public string Value1 { get; set; }
    public int Value2 { get; set; }
    public string ValueB1X { get; set; }
    public string ValueB2X { get; set; }
    ...
    public string ValueBnX { get; set; }
    public int Value3 { get; set; }  
}

I need to convert List of A into List of Result. Any idea how can that be done with LINQ? Basically what I need is this:

A[0] = |Value1|Value2|Value2|
        B[0]
        B[1]
        B[2]

A[1] = |Value1|Value2|Value2|
        B[0]
        B[1]
        B[2]

converted to

              +------------------------------------------------------+
     rowA[0]  | Value1 | Value2 |  B[0].X | B[1].X | B[1].X | Value3 |
     rowA[1]  | Value1 | Value2 |  B[0].X | B[1].X | B[1].X | Value3 |
1
  • 2
    Are there always going to be exactly three items in the list of Bs? Commented Sep 20, 2011 at 2:26

1 Answer 1

1

You need to know how many B you will have, because the Result class needs to be written to accomodate that number of items. So this is not a dynamic solution that would work any number of B like you seem to imply (1..n)

A better design would be

public class Result 
{
    public string Value1 { get; set; }     
    public int Value2 { get; set; }     
    public List<B> BValues { get; set; }
}

or, assuming the B Ids are always unique,

public class Result 
{
    public string Value1 { get; set; }     
    public int Value2 { get; set; }     
    public Dictionary<int, string> BValues { get; set; }
}

and then construct a dictionary -

List<A> list = GetList();
List<Result> result = list.Select(a =>
    new Result()
    {
        Value1 = a.Value1,
        Value2 = a.Value2,
        BValues = a.Values.ToDictionary(b => b.Id, b => b.X)
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Your Result class looks very similar to Class A that I started with. (except now its a Dictionary). Also I don't need IDs from class B, just Xs. (I added IDs just to show that B is complex class) What I really need is list of class B separated into variables and added to class A in the Result. Result class can be anonymous.
You can't dynamically create concrete types in a strongly typed language. You can easily put all the Xs into a collection - list, dictionary, etc - but you can't dynamically create properties. A good question to you would be why? How are you going to use this Result object?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.