从匿名类型中获取值

编程入门 行业动态 更新时间:2024-10-15 06:17:25
本文介绍了从匿名类型中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我声明了一个带有2个元素的匿名类型,如下所示,之后填充它。代码是浓缩的当然。

I have declared an anonymous type with 2 elements as follows and later filled it. Code is condensed of course.

public StudentNames Sub FillStudents() Dim st = From sts In db.StudentLists Order By studs.Last, studs.First _ Select studs.FullName, studs.StudentId StudentNames = sts.ToArray End Sub

我如何获得每个元素的价值 尝试使用StudentNames(0,1)并获得尝试操作在一个维数不正确的数组上。 我知道我可以将StudentNames声明为二维数组并循环遍历每个st来填充数组,但是sts .ToArray很简单。如果我使用单一尺寸的匿名类型数组,它是完美的,但我想保存StudentId供以后使用。 还有很多其他解决方案,但这个一个人现在和后来在程序中使用的代码少得多(如果我可以让它工作)。 顺便说一下,我搜索了匿名信息类型但它们都包含一个键,例如: Dim StudentNames = New With {Key .Name = st.FullName,.Stid = st.StudentId} 仍然需要遍历查询。如果可以的话,我宁愿避免这样做。

How do I get the value of each element Tried using StudentNames(0,1) and get "Attempted to operate on an array with the incorrect number of dimensions." I know I could declare StudentNames as a two dimensional array and loop through each st to fill the array, but sts.ToArray is so simple. It works perfect if I use a single dimensioned anonymous type array, but I would like to save the StudentId for later use. There are a lot of other solutions but this one uses a lot less code both now and later in the program (if I can get it to work). By the way, I've searched info on anonymous types but they all contain a key, such as: Dim StudentNames = New With {Key .Name = st.FullName, .Stid = st.StudentId} which still requires iterating through the query. I would prefer avoiding that if I can.

推荐答案

为什么你会认为Linq会返回一个二维数组?这就是你试图访问它的方式! 它返回的是一个匿名类型的一维数组,它有两个成员,所以你可以使用 StudentNames(0)返回一个匿名类型的实例,但你不能像访问数组元素一样访问类型成员! 我?如果我想在子例程之外使用它,我会声明一个辅助类并返回一个数组。 Why would you assume that the Linq would return a two dimensional array? That's how you are trying to access it! What it returns is a one dimensional array of an anonymous type which has two members, so you can use StudentNames(0) to return you an instance of the anonymous type, but you can't access the type members as if they were array elements! Me? I'd declare a "helper class" and return an array of that if I wanted to use it outside the subroutine.

更多推荐

从匿名类型中获取值

本文发布于:2023-11-07 00:38:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565077.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!