【发布时间】:2016-05-05 15:22:21
【问题描述】:
在 linq 查询中,我需要以某种方式将对在 linq 查询期间创建的对象的引用传递给在同一查询中创建的另一个类...我知道这个问题不清楚,所以请参阅下面的例子。
public class class1
public class class2
private _class1 as class1
public property OtherProperty1 as int
Public sub new(cls1 as class1)
_class1 = cls1
End Sub
End class
public property Property1 as int
public property Property2 as class2
End Class
Dim e as List(of class1) = (From row as datarow in dataTable.Rows
Select New class1 with {
.Property1 = row.Item("Property1"),
.Property2 = new class2(<<< ME >>>) with {
.OtherProperty1 = row.Item("OtherProperty1")
}
}).ToList()
因此,在上面的代码中,“>>”所在的位置,我需要将对正在创建的 class1 对象的引用传递给新的 class2 对象。
我知道我可以使用的另一种方法是在此查询期间创建 class1 对象,跳过对 class2 对象的引用。然后,稍后,在所有 class1 对象上使用 foreach 循环并使用新的 linq 查询来填充缺少的 class2 对象……它会起作用,但并不理想。我想一次填充所有内容,而不是一次完成其中的一部分。
--编辑-- 理想情况下,我不必更改现有类,因为它可能会在代码的其他部分产生不必要的副作用……如果我必须进行更改,我会愿意做一些我正在创建新构造函数的事情或属性,如某些答案中所建议的那样。
有什么想法吗?
【问题讨论】:
-
我对VB不太了解,但我认为您使用的是属性初始化程序,因此您可以先使用一段代码创建实例,然后使用创建的实例设置属性,然后返回实例。
-
正如您现在的代码一样,您在 Linq 查询中访问的
class1中缺少属性声明。