如何分配linq匿名类型变量

时间:2014-08-19 13:15:49

标签: vb.net linq

我有一个linq查询,它给了我一个System.Collections.Generic.IEnumerable(of <Anonymous Type>)。实际上我想创建一个类来更好地访问我想要的查询形式,但我失败了,声明一个应该保存查询结果的成员变量。我在我的类的Sub New()中使用的查询是(解释和c#version here:)

Dim jan1 = New DateTime(DateTime.Today.Year, 1, 1)
Dim startOfFirstWeek = jan1.AddDays(1 - CInt(jan1.DayOfWeek))
Dim weeks = Enumerable.Range(0, 54).[Select](Function(i) New With { _
    Key .weekStart = startOfFirstWeek.AddDays(i * 7) _
}).TakeWhile(Function(x) x.weekStart.Year <= jan1.Year).[Select](Function(x) New With { _
    x.weekStart, _
    Key .weekFinish = x.weekStart.AddDays(4) _
}).SkipWhile(Function(x) x.weekFinish < jan1.AddDays(1)).[Select](Function(x, i) New With { _
    x.weekStart, _
    x.weekFinish, _
    Key .weekNum = i + 1 _
})

我的班级应该如下:

Public Class WeekInfo

Private _weeks as ?????

end Class

有人能告诉我完成该任务的常用程序是什么以及如何为我的成员设置一个类型以访问周变量?

2 个答案:

答案 0 :(得分:0)

VB.Net anonymous types作为Object类型公开,因此您的变量将是:

Dim weeks As IEnumerable(Of Object)

您不会在您创建它们的函数之外的匿名类型字段上获得智能感知,但您可以动态访问它们,即

For Each week In weeks
    Console.WriteLine(week.weekStart + " " + week.weekFinish)
Next

如果需要在外部公开类型,则应该定义一个具体的类或结构。

答案 1 :(得分:0)

使您的WeekInfo类看起来像这样:     公共类WeekInfo

    Public Property WeekStart As Date
    Public Property WeekEnd As Date
    Public Property WeekNumber As Int32
End Class

然后使用linq查询加载它作为WeekInfo的列表:

    Dim jan1 = New DateTime(DateTime.Today.Year, 1, 1)
    Dim startOfFirstWeek = jan1.AddDays(1 - CInt(jan1.DayOfWeek))
    Dim weeks = Enumerable.Range(0, 54).Select(Function(i) New With { _
        Key .weekStart = startOfFirstWeek.AddDays(i * 7) _
    }).TakeWhile(Function(x) x.weekStart.Year <= jan1.Year).[Select](Function(x) New With { _
        x.weekStart, _
        Key .weekFinish = x.weekStart.AddDays(4) _
    }).SkipWhile(Function(x) x.weekFinish < jan1.AddDays(1)).[Select](Function(x, i) New WeekInfo With { _
        .WeekStart = x.weekStart, _
        .WeekEnd = x.weekFinish, _
        .WeekNumber = i + 1 _
    }).ToList()