Carl Reid
Carl Reid

Reputation: 780

LINQ select new list, pass parent class to property class

I'm not sure if I'm just searching the wrong thing or not, I just can't find an example of passing a parent class into a property of that class.

I've attempted to create a simple example which you can see below or view it at https://dotnetfiddle.net/uBGWgp.

I simply would like the Column class to know of its own parent Table, passing through the instance of it via the constructor (new Table()). See comment in code example where I wish to do this: /* Pass parent here? */

using System;
using System.Collections.Generic;
using System.Linq;


public class FakeDb{

    public class FakeColumn{
        public string ColumnName;
    }

    public class FakeTable{     
        public string TableName {get;set;}
        public IEnumerable<FakeColumn> Columns {get;set;}
    }

    public IEnumerable<FakeTable> Tables {get;set;}

    public FakeDb(){
        Tables = new List<FakeTable>(){
            new FakeTable(){
                TableName = "People",
                Columns = new List<FakeColumn>(){
                    new FakeColumn(){
                        ColumnName = "FirstName"    
                    },
                    new FakeColumn(){
                        ColumnName = "LastName" 
                    }
                }
            }
        };
    }

}

public class Table{
    public Guid TableGuid = Guid.NewGuid();

    public IEnumerable<Column> Columns;
}

public class Column{
    private Table _myTable;
    public Guid ColumneGuid = Guid.NewGuid();
    public Column(Table hostTable){
        _myTable = hostTable;
    }   
}

public class Program
{
    public static void Main()
    {
        var fakeDb = new FakeDb();

        var tableList = fakeDb.Tables.GroupBy(p => p.TableName, p => p, (tableName, values) => new {
            TableName = tableName,
            OtherValues = values
        }).Select(p => new Table(){
            Columns = p.OtherValues.Select(i => new Column(/* Pass parent here? */)).ToList()
        }).ToList();


    }
}

Upvotes: 0

Views: 873

Answers (1)

Johan
Johan

Reputation: 8266

Because you are not holding a reference to the new Table object you are creating, there is no way to do it in a single-lined query. However changing it to a multi-lined lambda expression will make this possible. Save your newly created table in a variable and then pass that variable into your Column's constructor.

You will have to do something like this

.Select(p => 
{
    var t = new Table();
    t.Columns = p.OtherValues.Select(i => new Column(t)).ToList();

    return t;
});

Demo: https://dotnetfiddle.net/1kKxMR

Upvotes: 3

Related Questions