将列表 linq 表达式转换为定义的列表类

本文关键字:列表 定义 转换 linq 表达式 | 更新日期: 2023-09-27 18:35:35

y 有这个类

Private Class MyClass
    Public Property propertyOne() as String
    Public Property propertyTwo() as String
    Public Property propertyN() as Integer
End Class

现在我想从 lambda 或 linq 表达式中填写一个 MyClass 列表,有些像这样......

    Dim myClassList as new List(Of MyClass)
    myClassList = (From lOtherList1 in MyOtherList1.GetAll()
                   join lOtherList2 in MyOterhList2.GetAll() on lOtherList1.Id Equals lOtherList2.Id
                   Select myClassList.Add(new MyClass With { .propertyOne = lOtherList1.Field1, 
                  .propertyTwo = lOtherList1.Field2,
                  .propertyN = lOtherList2.Field1 })).Tolist()

但是我收到此错误"表达式不产生值",我是如何做到的?

将列表 linq 表达式转换为定义的列表类

myClassList.Add查询中的部分是错误的,请按如下方式进行编辑:

Dim myClassList as new List(Of MyClass)
myClassList = (From lOtherList1 in MyOtherList1.GetAll()
               join lOtherList2 in MyOterhList2.GetAll() 
               on lOtherList1.Id Equals lOtherList2.Id
               Select new MyClass With 
               { 
               .propertyOne = lOtherList1.Field1, 
               .propertyTwo = lOtherList1.Field2,
               .propertyN = lOtherList2.Field1 
               })).Tolist()

您将执行以下操作:

myClassList = (From lOtherList1 in MyOtherList1.GetAll()
               Join lOtherList2 in MyOtherList2.GetAll()
               On lOtherList1.Id Equals lOtherList2.Id
               Select new MyClass With
               {
                   .propertyOne = lOtherList1.Field1,
                   .propertyTwo = lOtherList1.Field2,
                   .propertyN = lOtherList2.Field1
               }).ToList()

你几乎有正确的代码。您只需要删除对myClassList.Add()的调用。