我怎样才能更好地做到这一点(所以它确实有效:)
我有一个LINQ查询,其中包含一个基于用户首选项的订单。用户可以决定他们是否希望将结果命令为asc或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"***
我知道我可以把我的For Each循环放在If和Else中,但是两次使用相同的代码似乎很愚蠢。我知道你知道更好的方法:)
答案 0 :(得分:1)
在Dim mydat
语句之前定义If
。当代码到达for循环时,它超出了范围。
答案 1 :(得分:0)
使用扩展方法和基于函数的LINQ(我的VB生锈了)
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);