如何将c# Linq转换为VB.NET

本文关键字:VB NET 转换 Linq | 更新日期: 2023-09-27 17:49:34

有人能帮我把这个c# Linq-u转换成VB吗?NET代码

var groupedItems = from item in LinqueResult
                    orderby item.Category
                    group item by 
                        item.GetType().GetProperty("Test").GetValue(item).ToString()
                        into groupPropertie 
                    select new KeyedList<string, ItemToDisplay>(groupPropertie);

感谢更新:

ken2K我知道,但我没有得到一个工作代码与在线转换器

到目前为止,我是靠自己的力量获得的

Public Function GroupedPhotos(LinqueResult As List(Of ItemToDisplay), GroupMember As [String]) As List(Of KeyedList(Of String, ItemToDisplay))
    Dim groupedItems = From groupPropertie In From item In LinqueResult
                                              Order By item.Category
                                              Group item By item.GetType.GetProperty(GroupMember).GetValue(item).ToString() Into Group
                                              Select New KeyedList(Of String, ItemToDisplay)(groupPropertie)
    Return New List(Of KeyedList(Of String, ItemToDisplay))(groupedItems)
End Function

我得到这个错误:

错误1:范围变量名不能匹配'Object'类成员的名称。C:'xxx' mainpage . example .vb 53 118 LongListSelectorFreeLancVBasic

如何将c# Linq转换为VB.NET

在线转换器烂透了。正确的翻译是:

Dim groupedItems = from item in LinqueResult
                   order by item.Category
                   let test = item.GetType().GetProperty("Test").GetValue(item).ToString() 
                   group item by test into groupPropertie = Group
                   select new KeyedList(Of string, ItemToDisplay)(groupPropertie)

注意,必须使用let子句将item.GetType()...ToString()的结果绑定到另一个名称。否则,VB。Net试图创建一个名为ToString的局部变量,然后抱怨ToString不能使用,因为Object上有一个成员使用这个名称。

在这一行中使用let可以使IMHO更容易阅读。

group语法也不同:要使用命名组,必须使用your_group_name = Group。但是,由于您实际上没有对groupProertie做任何操作,您也可以直接使用

...
group item by test into Group
select new KeyedList(Of string, ItemToDisplay)(Group)

试试这个

Dim groupedItems = From groupPropertie In From item In LinqueResultOrder By item.CategoryGroup item By item.[GetType]().GetProperty("Test").GetValue(item).ToString()New KeyedList(Of String, ItemToDisplay)(groupPropertie)

将编译后的版本插入任何反编译器(DotNetPeek, JustDecompile或reflector),然后要求它显示VB中的代码

链接内容基本相同,除了vb.net通常大写关键字:

Dim groupedItems = From item In LinqueResult
                    OrderBy item.Category
                    Group item By item.GetType()
                        .GetProperty("Test")
                        .GetValue(item)
                        .ToString() 
                    Into groupPropertie 
                    Select New KeyedList(Of String, ItemToDisplay)(groupPropertie)