LINQ Query Based on Custom Settings

How can I do it better (so it really works :)

I have a LINQ query that includes an order based on user preference. The user can decide whether they want the results to be sorted by 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 that I could put the โ€œEvery forโ€ loop inside the โ€œAndโ€ and โ€œOtherwiseโ€, but it seems silly to have the same code twice. I know you know the best way :)

+3
source share
2 answers

Use extension method and function-based LINQ (my VB is rusty like 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 the request as follows:

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

Or in C #:

var mydat = dv.ITRS.OrderbyString(item => item.Date, fuserclass.SortOrder);
0
source

Dim mydat If. , for.

+1

Source: https://habr.com/ru/post/1745023/


All Articles