我在变量DataTable
中有dtLatencyValues
。
我从此DataTable
中选择数据到匿名类型列表中:
Dim _Latency = dtLatencyValues.AsEnumerable()
.Where(Function(x) x("Customer_Name") = str1(0).CustName AndAlso x("Site_Name") = str1(j).sitname)
.Select(Function(x) New With
{
.CommLat = x("Committed_Value"),
.ActLat = x("ActualLatencyVal"),
.ToContry = x("Site_To_Name")
})
.OrderBy(Function(a) a.ToContry)
.DefaultIfEmpty().ToList()
我想补充一下:
Dim temp = New With {.CommLat = "-", .ActLat = "-", .ToContry = str1(j).sitname}
进入我的_Latency
列表,然后从最终的_Latency
列表中检索数据。
答案 0 :(得分:1)
Dim _Latency = dtLatencyValues.AsEnumerable()...ToList()
Dim temp = New With {.CommLat = "-", .ActLat = "-", .ToContry = str1(j).sitname}
_Latency.Insert(0, temp) ' insert as first element '
' or '
_Latency.Add(temp) ' insert as last element '
答案 1 :(得分:0)
您可能希望设置Option Strict On
以帮助避免此类问题。您的问题是LINQ查询创建的匿名类型的属性都被键入为Object
,因为DataRow.Item
(代码中的x("field name")
)返回Object
。如果要添加商品,则需要匹配匿名类型,而AnonymousType(Of Object, Object, Object)
与AnonymousType(Of String, String, String)
不匹配。
如果您更改查询以使用正确的类型,则应该能够更轻松地添加新项目,例如(不确定这些是否是您数据的正确类型!):
Dim _Latency = dtLatencyValues.AsEnumerable() _
.Where(Function(x) x.Field(Of String)("Customer_Name") = str1(0).CustName AndAlso x.Field(Of String)("Site_Name") = str1(j).sitname) _
.Select(Function(x) New With
{
.CommLat = x.Field(Of String)("Committed_Value"),
.ActLat = x.Field(Of String)("ActualLatencyVal"),
.ToContry = x.Field(Of String)("Site_To_Name")
}) _
.OrderBy(Function(a) a.ToContry) _
.DefaultIfEmpty().ToList()
_Latency.Add(New With {.CommLat = "-", .ActLat = "-", .ToContry = str1(j).sitname})
您可能需要添加System.Data.DataSetExtensions.dll
的引用,才能使.Field(Of String)
次来电。
修改强>
这是一个完整的工作示例 - VS2013控制台项目。
Option Strict On
Option Explicit On
Option Infer On
Module Module1
Sub Main()
Dim dtLatencyValues = New DataTable()
dtLatencyValues.Columns.Add("Customer_Name", GetType(String))
dtLatencyValues.Columns.Add("Site_Name", GetType(String))
dtLatencyValues.Columns.Add("Committed_Value", GetType(String))
dtLatencyValues.Columns.Add("ActualLatencyVal", GetType(String))
dtLatencyValues.Columns.Add("Site_To_Name", GetType(String))
dtLatencyValues.Rows.Add("CustA", "SiteA", "Com1", "Act1", "STN1")
dtLatencyValues.Rows.Add("CustA", "SiteA", "Com2", "Act2", "STN2")
dtLatencyValues.Rows.Add("CustA", "SiteB", "Com1", "Act1", "STN1")
dtLatencyValues.Rows.Add("CustB", "SiteB", "Com1", "Act1", "STN1")
Dim custName = "CustA"
Dim siteName = "SiteA"
Dim _Latency = dtLatencyValues.AsEnumerable() _
.Where(Function(x) x.Field(Of String)("Customer_Name") = custName AndAlso x.Field(Of String)("Site_Name") = siteName) _
.Select(Function(x) New With
{
.CommLat = x.Field(Of String)("Committed_Value"),
.ActLat = x.Field(Of String)("ActualLatencyVal"),
.ToContry = x.Field(Of String)("Site_To_Name")
}) _
.OrderBy(Function(a) a.ToContry) _
.DefaultIfEmpty().ToList()
_Latency.Add(New With {.CommLat = "-", .ActLat = "-", .ToContry = siteName})
End Sub
End Module
在End Sub
行设置断点并检查_Latency
显示: