如果我有2个类并希望从每个类中获取2个属性,并将它们组合成一个单独的集合,那么如何使用linq完成?
说两个类是:
class guitars
public ID
public title
public manufacturer
end class
class drums
public ID
public title
public manufacturer
end class
我尝试了这个,但它不起作用:
Private Interface Instruments
Property ID As String
Property name As String
End Interface
Dim results = From item In guitars _
Select New Instruments() With _
{ _
.ID = item.ID, _
.name = item.Title _
}
Dim results2 = From item In drums _
Select New Instruments() With _
{ _
.ID = item.ID, _
.name = item.Title _
}
Dim combined = results + results2
答案 0 :(得分:4)
你可以使它简单得多。
让这两个类实现IInstrument
接口
然后你可以写
guitars.Cast(Of IInstrument)().Concat(drums)
答案 1 :(得分:1)
Union或Concat取决于您是否愿意在列表中允许重复。
http://msdn.microsoft.com/en-us/library/vstudio/bb763068.aspx
Dim Combined = results.Union(results2) ' no duplicates allowed
Dim Combined = results.Concat(results2) 'duplicates allowed
编辑:在MatthewWhited的要求下添加了Concat。他完全正确。根据MSDN,该列表是不同的。