aaa
aaa

Reputation: 1124

No property or field 'x' exists in type 'Object' - Dynamic linq

I have a class that has a property of type Object.

class Test
{
    public Object obj { get; set; } // This "obj" can be of type Test1 or other type 
    .....
}

class Test1
{
    public int a = 1;
    public int b = 2;
}

List<Test> myList = new List<Test>{new Test() {obj = new Test1()}} // This contains some values.

Now I want to sort "myList" based on "obj" values with sort string known dynamically using:

myList.AsQueryable().OrderBy("obj.a ascending, obj.b descending");

This is when I get error. I have tried type casting but that does not help.

Upvotes: 0

Views: 3815

Answers (4)

Scott
Scott

Reputation: 21

I had a similar error, but in my case I just had a list of objects (List) and I had to sort it dynamically. I used activator to create an instance of IList of the type of object, added all the objects, then sorted it dynamically.

Upvotes: 1

Sachin
Sachin

Reputation: 40970

The first thing is myList expect the object of type Test not Test1. You need to set the value of obj property of Test like this

List<Test> myList = new List<Test>{new Test(){ obj=new Test1() }};

Now you want to apply the sorting over the Test1 object so you need to cast that object into type of Test1 like this and then apply the sorting.

myList.OrderBy(x => ((Test1)x.obj).a).OrderByDescending(x => ((Test1)x.obj).b);

Upvotes: 0

TyCobb
TyCobb

Reputation: 9089

The compiler doesn't know what obj is because it is of type Object.

The only way around this is either implementing an interface on your types that will have a common a and b or a using dynamic instead of Object. However, using dynamic is not the best way to go about these issues unless you absolutely have to.

Upvotes: 0

Marko Juvančič
Marko Juvančič

Reputation: 5890

The way to sort in LINQ is:

var sortedList = myList.OrderBy(obj => obj.a).ThenByDescending(obj => obj.b).ToList();

If "dynamic" in the title of your question refers to building your condition in run-time, maybe you should look at Dynamic LINQ.

Upvotes: 1

Related Questions