background image

  但是,在实际开发过程中,我们并不一定能够如此轻松的将某个特定类型的数据作为
数据源,往往需要组合两种对象进行联合显示。例如,我们在显示评论列表时往往还会要显
示发表用户的个人信息。由于

C# 3.0 中已经支持了匿名对象,所以我们可以这样做:

protected void Page_Load(object sender, EventArgs e)
{
    List<Comment> comments = GetComments();
    List<User> users = GetUsers();
    this.rptComments.DataSource = from c in comments
                                  from u in users
                                  where c.UserID == u.UserID
                                  order by c.CreateTime
                                  select new
                                  {
                                      Title = c.Title,
                                      Content = c.Content,
                                      NickName = u.NickName
                                  };
    this.rptComments.DataBind();
}
  我们通过

LINQ 级联 Comment 和 User 数据集,可以轻松地构造出构造出作为数据源的

匿名对象集合(有没有看出

LINQ 的美妙?)。上面的匿名对象将包含 Title,Content 和

NickName 几个公有属性,因此在页面中仍旧使用 Eval 来获取数据,不提。
  不过我几乎可以肯定,又有人要叫了起来:

“LINQ 没有用!我们不用 LINQ!Eval 性

能差!我们不用

Eval!

”。好吧,那么我免为其难地为他们用“最踏实”的技术重新实现一遍:

private Dictionary<int, User> m_users;
protected User GetUser(int userId)
{
    return this.m_users[userId];
}
protected void Page_Load(object sender, EventArgs e)
{
    List<Comment> comments = GetComments();
    List<User> users = GetUsers();
    this.m_users = new Dictionary<int, User>();
    foreach (User u in users)
    {
        this.m_users[u.UserID] = u;
    }
    this.rptComments.DataSource = comments;
    this.rptComments.DataBind();
}
<asp:Repeater runat="server" ID="rptComments">
    <ItemTemplate>
        Title: <%# (Container.DataItem as Comment).Title %><br />