假设我的视图中有一个下拉列表。不同的选择将使用需要返回到视图的linq结果。
我已经完成了查看页面。现在在我的控制器上,我有点卡住了。 我知道var不能用作“全局”变量声明。但是我该怎么办呢?
这是我的代码:
Private Sub cmdDeleteA_Click()
'declare the variables
Dim findvalue As Range
Dim cDelete As VbMsgBoxResult
Dim cNum As Integer
'error statement
On Error GoTo errHandler:
'check for values
If Reg1.Value = "" Or Reg4.Value = "" Then
MsgBox "There is not data to delete"
Exit Sub
End If
'give the user a chance to change their mind
cDelete = MsgBox("Are you sure that you want to delete this training", vbYesNo + vbDefaultButton2, "Are you sure????")
If cDelete = vbYes Then
'the next few paragraphs until "Loop While.." was recently added
'set the search range and find the row (2 layers)
Dim rgF As Range
Set rgF = Sheet2.Range("F:F")
Set findvalue = rgF.Find(What:=Reg4, LookIn:=xlValues, LookAt:=xlWhole)
'If the ID doesn't exist, get out of there
If findvalue Is Nothing Then
Debug.Print "No one has that ID anymore"
Exit Sub
End If
Do
'delete the row that has the ID
findvalue.EntireRow.Delete
'find the next instance
Set findvalue = rgF.FindNext(findvalue)
Loop While Not findvalue Is Nothing
End If
'clear the controls
cNum = 9
For x = 1 To cNum
Me.Controls("Reg" & x).Value = ""
Next
'run the filter
AdvFilter
'add the values to the listbox
lstLookUp.RowSource = ""
lstLookUp.RowSource = "Staff_Filter"
'error block
On Error GoTo 0
Exit Sub
errHandler::
MsgBox "An Error has Occurred " & vbCrLf & "The error number is: " _
& Err.Number & vbCrLf & Err.Description & vbCrLf & _
"Please notify the administrator"
End Sub
答案 0 :(得分:1)
不幸的是,你不能。有多种选择。使用dynamic
或返回一个对象。例如。例如IEnumerable<object>
,IList<object>
。或者,您可以使用ProductName和UnitPrice作为poco创建一个Product模型。
编辑:
这是一个很老套,但可以使用。
void GetObject<T>(object anonymousObject, T cast)
{
return (T) anonymousObject;
}
在模型上,您可以像这样呼叫:
object linqResult;
// retrieve linqResult data;
....
var obj = GetObject(linqResult, new { ProductName = "Honda", UnitPrice = 20.0 };
This variable can be accessed as
Console.WriteLine(obj.ProductName);
答案 1 :(得分:1)
您可以声明要使用的自定义类型,而不是匿名类型:
public class ProductPrice
{
public string Name { get; set; }
public decimal Price { get; set; }
}
然后LinqResult
被声明为
IEnumarable<ProductPrice> LinqResult;
您将select
更改为
select new ProductPrice { Name = Products.Product name, Price = Products.UnitPrice };
答案 2 :(得分:0)
如果那确实是您的全部操作,则无需这样做。只需将LinqResult =
替换为return
。
但是,如果您确实需要确定类型,我通常会在设置变量的位置临时声明该变量:
var LinqResult = from ...
然后,在Visual Studio中,将光标悬停在变量名称上,它将告诉我类型。然后更改代码,并使用类型声明变量。
在这种特定情况下,它最终将成为匿名类型的IEnumerable
,我认为您实际上不能声明,至少不能直接声明。 here对此有一些讨论。
答案 3 :(得分:0)
如果在切换块之后您不需要对变量做任何事情,我只会从切换块内部返回,例如
switch (Linq)
{
case "Most Expensive":
return from Products in northwindEntities.Products
...
case "Above Average":
return from Products in northwindEntities.Products
....
}
return null;
否则,除非声明编译器可以从赋值中找出类型,否则在声明变量时必须定义类型。
您可能想使用List | IEnumerable | IEnumberable或定义结果类型。