tags:

views:

45

answers:

2

How can I do this better (so it actually works : )

I have a LINQ Query that includes an order by that is based on a user preference. The user can decide if they would like the results ordered asc or desc.

If fuserclass.SortOrder = "Ascending" Then
   Dim mydat = (From c In dc.ITRS Order By c.Date Ascending Select c)
Else
   Dim mydat = (From c In dc.ITRS Order By c.Date Descending Select c)
End If

For each mydata in mydat ***<<<error "mydat is not declared"***

I know I could put my For Each loop inside the If and Else, but that seems silly to have the same code twice. I know you know of a better way : )

+1  A: 

Define Dim mydat before the If statement. It is out of scope when your code reaches the for loop.

Taylor Leese
Thanks so much, I had another situation that had needed to sort on multiple fields that were not always the same and this solution works! With LINQ, this Dim mydat = (From c In dc.ITRS)doesn't actually pull any data until my for each loop right?
Chris Phelps
Yes, your LINQ query uses deferred execution.
Taylor Leese
A: 

Use an extension method, and function-based LINQ (my VB is rusty as hell)

VB.NET:

<ExtensionAttribute> _
Public Shared Function OrderByString(Of TSource, TKey) ( _
source As IEnumerable(Of TSource), _
keySelector As Func(Of TSource, TKey) _
    strType As String) As IOrderedEnumerable(Of TSource)

    If strType = "Ascending" Then
        return source.OrderBy(keySelector)
    Else
        return source.OrderByDescending(keySelector)
    End If
End Function

C#.NET:

public static IOrderedEnumerable<TSource> OrderByString(
    this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector,
    string strType)
{
    if (strType == "Ascending")
        return source.OrderBy(keySelector);
    return source.OrderByDescending(keySelector);
}

Then call your query like this:

Dim mydat = dc.ITRS.OrderByString(Function(item) item.Date, fuserclass.SortOrder)

Or on C#:

var mydat = dv.ITRS.OrderbyString(item => item.Date, fuserclass.SortOrder);
Aren
Actually the first answer worked (totally appreciate it Taylor L), but since you put so much effort into this answer, I had to try it. Took me a minute to learn about extension methods, but your solution works GREAT...thank you so much!
Chris Phelps
Glad I could help, that extension method is useful too because you can chain it together as well. `OrderByString(...).Skip(10).Take(5)`
Aren