Sushant Yelpale
Sushant Yelpale

Reputation: 889

Compile time Type declaration without using dynamic in C#

I have 2 Models like Below,

public class AClass
{
    public int prop { get; set; }
    public virtual List<BClass> bClass { get; set; }
}

public class BClass
{
    public int prop1 { get; set; }
    public int prop2 { get; set; }
}

Used these models in linq query

var data = testList.GroupBy(e => e.TestProp1).Select(g=> new AClass
{
    prop = g.Key,
    bClass = g.GroupBy(p=> p.TestProp2).Select(g1 => new BClass {
        prop1 = g1.FirstOrDefault().TestProp1,
        prop2 = g1.FirstOrDefault().TestProp2
    }).ToList()
}).ToList();

Now, there is a requirement to add a new property prop3 in BClass without affecting to original BClass. So, I created inherited CClass and used it in linq,

public class CClass : BClass
{
    public int prop3 { get; set; }
}

var data1 = testList.GroupBy(e => e.TestProp1).Select(g=> new AClass
{
    prop = g.Key,
    bClass = g.GroupBy(p=> p.TestProp2).Select(g1 => new CClass {
        prop1 = g1.FirstOrDefault().TestProp1,
        prop2 = g1.FirstOrDefault().TestProp2
    }).ToList()
}).ToList();

In this scenario, bClass = g.GroupBy(p => p.TestProp2, (key1, g1) => new CClass line giving error, Cannot implicitly convert type 'System.Collections.Generic.List<TestApp.CClass>' to 'System.Collections.Generic.List<TestApp.BClass>'

* Solution I Tried: *

I Replaced following line from AClass

public virtual List<BClass> bClass { get; set; }`

with

public virtual dynamic bClass { get; set; }

it worked.

But, just for curiosity, without declaring it as dynamic property, How can I achieve it?

Upvotes: 0

Views: 38

Answers (1)

Sweeper
Sweeper

Reputation: 274360

There is no need to use dynamic at all. You just need to tell the compiler that you want a BClass from the second call to Select:

var data1 = testList.GroupBy(e => e.TestProp1).Select(g=> new AClass
{
    prop = g.Key,
    // this line here! Note the cast
    bClass = g.GroupBy(p=> p.TestProp2).Select(g1 => (BClass)(new CClass {
        prop1 = g1.FirstOrDefault().TestProp1,
        prop2 = g1.FirstOrDefault().TestProp2,
        prop3 = ... // why don't you also set prop3?

    })).ToList()
}).ToList();

Upvotes: 3

Related Questions