gpt4 book ai didi

asp.net - 基于用户首选项的LINQ查询

转载 作者:行者123 更新时间:2023-12-02 04:15:59 24 4
gpt4 key购买 nike

我怎样才能做得更好(所以它实际上可以工作:)

我有一个LINQ查询,其中包括基于用户偏好的订单。用户可以决定是否要按升序或降序排列结果。

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"***

我知道我可以将For Each循环放在If和Else内,但这对于两次具有相同代码的做法似乎很可笑。我知道您知道更好的方法:)

最佳答案

使用扩展方法和基于函数的LINQ(我的VB像 hell 一样使用rust )

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);
}

然后像这样调用您的查询:
Dim mydat = dc.ITRS.OrderByString(Function(item) item.Date, fuserclass.SortOrder)

或在C#上:
var mydat = dv.ITRS.OrderbyString(item => item.Date, fuserclass.SortOrder);

关于asp.net - 基于用户首选项的LINQ查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2815297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com