简体   繁体   中英

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.

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 .

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM