0

I haven't used LINQ extensively but the more I use it the more I realize how powerful it can be. Using the LinqDataSource.OrderBy clause is obviously easy if you want to sort from a property on the bounded items but what if you want to sort the items based on a method return? Take this class for instance (please ignore the quirky design - it's just used to emphasize my point):

public class DataItem
{
    private string Id { get; set; }

    private int SortValue { get; set; }

    public DataItem(string id, int sortValue)
    {
        this.Id = id;
        this.SortValue = sortValue;
    }

    public int GetSortValue()
    {
        return SortValue;
    }
}

Is there a way that I can set the orderby expression on the LinqDataSource so that it uses the value returned from GetSortValue (i.e order by other members than properties) but without altering the DataItem class?

Stig Perez
  • 3,595
  • 4
  • 23
  • 36

2 Answers2

1

If the method has no parameters you could wrap it with a property?

public int SortOrderBy { get { return GetSortValue(); } }

Edit: This will also work if the parameters are constants or class fields/properties.

Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
  • Hi Jackson, Indeed I could wrap the method in a property - unfortunately (and I probably should have mentioned this before) I can't modify the DataItem class. I was wondering if there was a way to set the order property without changing the Dataitem class – Stig Perez Nov 23 '10 at 11:20
  • Not that I can see I'm afraid. – Jackson Pope Nov 23 '10 at 11:27
0

The MSDN docs mention that it is indeed possible to do custom sorting but I might have misinterpreted your question.

David K.
  • 6,153
  • 10
  • 47
  • 78
  • 1
    You linked the reference for `IEnumerable.OrderBy()` (LINQ), meawhile OP is talking about `System.Web.UI.WebControls.LinqDataSource` – abatishchev Nov 23 '10 at 10:49