0
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();
Skyx
  • 103
  • 12
  • How do you get the objects in `_list`? – Jerodev May 03 '18 at 09:17
  • 3
    `List.OrderBy( ... ).ToList()` is inefficient because it creates a copy, instead call `List.Sort()` directly, though it doesn't use a property-selector to determine what to sort by, you can provide your own comparator function. – Dai May 03 '18 at 09:20
  • Do you look for a way to query upon the name of a property, e.g. `string name = attribute1; list.OrderBy(name)`? – MakePeaceGreatAgain May 03 '18 at 09:22
  • 4
    Possible duplicate of [How do I specify the Linq OrderBy argument dynamically?](https://stackoverflow.com/questions/7265186/how-do-i-specify-the-linq-orderby-argument-dynamically) – Rotem May 03 '18 at 09:23
  • Yes, thats exactly what I want. But the attribute1 is a property and not a string. – Skyx May 03 '18 at 09:23
  • no you can't do `_list.OrderBy(x => x.myAttribute).ToList();` because **myAttribute** is not the property of the **x** which is **data**. – Vincent Elbert Budiman May 03 '18 at 09:24
  • Thanks guys. The post of Rotem just solve the problem. – Skyx May 03 '18 at 09:30

2 Answers2

4

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();
Pelin
  • 936
  • 5
  • 12
-2

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();
Sylvia
  • 80
  • 5