创建的匿名类型在VB列表 [英] Creating a list of Anonymous Type in VB

查看:184
本文介绍了创建的匿名类型在VB列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个匿名类型的列表,例如:

I'd like to create a list of an anonymous type, for example:

Dim lineItem = New With {.Name = myFile(index).Last_Name & ", " & myFile(index).First_Name, _
                         .StartDate = myFile(index).Day,
                         .EndDate = myFile(index).Day}

我已经创建了一个匿名类型。现在我想将它添加到该类型的列表。我如何声明该类型的列表?

I have created that anonymous type. Now I'd like to add it to a list of that type. How do I declare a list of that type?

推荐答案

下面是从一个匿名类型创建一个匿名类型的列表的便捷方法。

Here's a handy method for creating a list of an anonymous type from a single anonymous type.

Public Function CreateListFromSingle(Of T)(ByVal p1 As T) As List(Of T)
  Dim list As New List(Of T)
  list.Add(p1)
  return List
End Function

现在你可以做以下

Dim list = CreateListFromSingle(dsResource)

修改 OP就想办法创造一个元素之前创建列表。

EDIT OP wanted a way to create the list before creating an element.

有2种方法来做到这一点。您可以使用下面的code创建一个空的列表。它接壤哈克因为你传递参数,你永远不打算使用,但它的工作原理。

There are 2 ways to do this. You can use the following code to create an empty list. It borders on hacky because you are passing parameters you don't ever intend to use but it works.

  Public Function CreateEmptyList(Of T)(ByVal unused As T) As List(Of T)
    Return New List(Of T)()
  End Function

  Dim x = CreateEmptyList(New With { .Name = String.Empty, .ID = 42 })

这篇关于创建的匿名类型在VB列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆