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

时间:2012-05-26 16:09:39

标签: c# .net vb.net linq lambda

你有这个班级

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()

但我得到这个错误“表达式不会产生值”,我是如何制作的?

2 个答案:

答案 0 :(得分:0)

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()

答案 1 :(得分:0)

您将执行以下操作:

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()的调用。