简体   繁体   中英

Adding items from dataset to list

I have the following working code on C# to fill a list:

[WebMethod]
public List<object> GetCheckTypes(int opc)
{
    List<object> result = new List<object>();
    DataTable results = new DataTable();

    results = conn.GetDataSetBySP("SP_NAME",
        new object[] { "@Opc" },
        new object[] { 1}).Tables[0];

    foreach (DataRow i in results.Rows)
    {
        result.Add(new { Id = i["Id"], Name = i["Name "] });
    }
}

But I want to do the same thing using VB. I have the following code:

<WebMethod>
Public Function GetCheckTypes(ByVal opc As Integer) As List(Of Object)

    Dim result As List(Of Object) = New List(Of Object)()
    Dim results As DataTable = New DataTable()

    results = conn.GetDataSetBySP("SP_NAME", New Object() {"@Opc"}, New Object() {1}).Tables(0)

     For Each i As DataRow In results.Rows
         result.Add(New With {Key
             .Id = i("Id"), Key
             .Name = i("Name ")})
    Next
End Function

I'm having problems with result.add part in specific with New With {Key... etc..

What could be the problem or which is the better way to fill a list.

Your issue is with how VB.NET does multi-line code. You have to append a _ at the end of a line that will be continued on the next one, which is something you do not have to do in C#.

The following should work:

result.Add(New With {Key _
    .Id = i("Id"), Key _
    .Name = i("Name ")})

VB.NET also has implicit line continuations (for the last few versions), so you don't have to include line continuation characters if you conform to where VB will infer a line continuation - for example:

For Each i As DataRow In results.Rows
    result.Add(New With {
        Key .Id = i("Id"),
        Key .Name = i("Name ")
    })
Next i

See: https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/program-structure/how-to-break-and-combine-statements-in-code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM