Skyx
Skyx

Reputation: 103

C# Linq OrderBy(x => x.property)

public class data() {
   public string attribute1 { get; set; }
   public string attribute2 { get; set; }
   public string attribute3 { get; set; }
}

I have a list that orders the given attribute.

_list.OrderBy(x => x.attribute1).ToList();

But I want to define the object first and then execute order in order with the give object. I am wondering if this is possible. for example:

object myAttribute = attribute1;
_list.OrderBy(x => x.myAttribute).ToList();

Upvotes: 0

Views: 1942

Answers (2)

Sylvia
Sylvia

Reputation: 80

Whatever you are trying that is quite impossible i guess but you can define myAttribute properties in data class try this if it would work for you.

public class data
{
     public string attribute1 { get; set; }
     public string attribute2 { get; set; }
     public string attribute3 { get; set; }

     public object myAttribute { get; set; }
}

_list.OrderBy(x => x.myAttribute).ToList();

Upvotes: -2

Pelin
Pelin

Reputation: 966

If you need to create dynamic order by statements, you can do it like this:

Func<Item, Object> orderBy = null;

if(...)
   orderBy = item => item.attribute1 ;
else 
  orderBy = item => item.attribute2;

_list.OrderBy(orderBy).ToList();

Upvotes: 4

Related Questions