我正在从三个对象列表中返回这样的列表*感谢@sehe
`var joined = from p in personList
join par in relations
on p.Id equals par.PersonId
join a in addressList
on a.Id equals par.AddressId
select new { Person = p, Address = a };`
如何设置join作为listview的数据源并访问aspx页面中的属性?
好的,这里有一些代码可能会有所帮助,因为我得到了两个不同的答案。
//背后的代码
protected void Page_Init(object sender, EventArgs e)
{
List<Customer> customers = Customer.GetAllCustomers();
List<Address> addresses = Address.GetAllAddresses();
List<AddressRelation> addressRelations = AddressRelation.GetAllAddressRelations();
var results = from c in customers
join rel in addressRelations
on c.CustomerID equals rel.CustomerID
join a in addresses
on rel.CustomerAddressID equals a.CustomerAddressID
select new
{
FirstName = c.FirstName,
LastName = c.LastName,
PhoneNumber = c.PhoneNumber,
AddressLine = a.AddressLine1,
CustomerCity = a.City,
CustomerZip = a.ZipCode
};
ListView1.DataSource = results;
ListView1.DataBind();
这是我的列表视图:
`<asp:ListView ID="ListView1" runat="server" >`
`<LayoutTemplate>`
<ul style="float:left; width:250px">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><%# Eval("FirstName") %></li>
<li><%# Eval("AddressLine") %></li>
</ItemTemplate>
<ItemSeparatorTemplate><hr /></ItemSeparatorTemplate>
</asp:ListView>
答案 0 :(得分:3)
您只需设置ListView.DataSource = joined
,然后拨打DataBind()
即可通过Eval()
或Bind()
在ListView模板中访问它们。有关其他信息,请参阅MSDN documentation for the ListView control实例
答案 1 :(得分:1)
要回答问题的第一部分,匿名类型可以像任何其他类型一样用作数据源。 ASP.NET将反映源代码并找到它需要的任何属性。
myListView.DataSource = joined;
myListView.DataBind();
然后,要在ListView中访问这些属性,只需使用Bind和Eval。这里有一些documentation on databinding让你入门
答案 2 :(得分:0)
这里有两个问题:
您尚未完全枚举该集合 - 您应该调用.ToList()
或.ToArray()
等聚合器。
此外,您正在创建一个匿名对象作为结果。在该代码的特定范围之外,什么都不知道该对象包含哪些属性。如果要在其他位置使用该对象,则应切换到具有已知属性的预定义类。