我發現這個線程非常有幫助。這是我使用外部中繼器和內部中繼器的概念驗證解決方案。
如何使用LINQ分組填充嵌套數據綁定控件
<form id="form1" runat="server">
<div>
<table>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<tr>
<td>
<%# Eval("key.FavoriteColor")%>
</td>
<td>
<%# Eval("key.FavoriteFood")%>
</td>
<td colspan="2"></td>
</tr>
<asp:Repeater ID="Repeater2" DataSource='<%# Eval("value") %>' runat="server">
<ItemTemplate>
<tr>
<td>
<%# Eval("ID") %>
</td>
<td>
<%# Eval("Name") %>
</td>
<td>
<%# Eval("FavoriteColor") %>
</td>
<td>
<%# Eval("FavoriteFood") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
</form>
public partial class WebForm1 : Page
{
private List<Child> CreateChildren()
{
List<Child> children = new List<Child>();
children.Add(new Child
{
FavoriteColor = Child.Color.Green,
FavoriteFood = Child.Food.IceCream,
Name = "Sam",
ID = 1,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Blue,
FavoriteFood = Child.Food.Hamburgers,
Name = "Tom",
ID = 2,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Blue,
FavoriteFood = Child.Food.Pizza,
Name = "Fred",
ID = 3,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Orange,
FavoriteFood = Child.Food.Tacos,
Name = "Mark",
ID = 4,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Green,
FavoriteFood = Child.Food.Pizza,
Name = "Harry",
ID = 5,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Pink,
FavoriteFood = Child.Food.Pizza,
Name = "Natalie",
ID = 6,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Green,
FavoriteFood = Child.Food.Pizza,
Name = "Amy",
ID = 7,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Yellow,
FavoriteFood = Child.Food.Hamburgers,
Name = "Katie",
ID = 8,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Red,
FavoriteFood = Child.Food.IceCream,
Name = "Betty",
ID = 9,
});
children.Add(new Child
{
FavoriteColor = Child.Color.Pink,
FavoriteFood = Child.Food.Pizza,
Name = "Erica",
ID = 10,
});
return children;
}
protected void Page_Load(object sender, EventArgs e)
{
List<Child> children = CreateChildren();
// Use LINQ to create the groupings.
var query = (from c in children
group c by new
{
c.FavoriteColor,
c.FavoriteFood,
}
into g select g).ToDictionary(g => g.Key, g => g.ToList());
// Here is the same code using LINQ chain methods.
// var query = children.GroupBy(c => new { c.FavoriteColor, c.FavoriteFood }).Select(g => g).ToDictionary(g => g.Key, g => g.ToList());
Repeater1.DataSource = query;
Repeater1.DataBind();
}
}
public class Child
{
public enum Color
{
Black,
Blue,
Brown,
Green,
Orange,
Pink,
Purple,
Red,
Yellow,
White,
}
public enum Food
{
Chicken,
Hamburgers,
IceCream,
Pizza,
Tacos,
}
public int ID { get; set; }
public string Name { get; set; }
public Color FavoriteColor { get; set; }
public Food FavoriteFood { get; set; }
}
搞清楚如何與ToDictionary表達訪問匿名成員後,我意識到我仍然沒有那種獲得我所需要的內gridview的其他成員。 我爲這個鍵創建了兩個成員類,然後在每個轉發器迭代過濾了內部gridview的原始數據表。 – Matt
使用匿名類很好。我們不需要使用反射。 –