4

在下面的源代码中,我从users集合中选择了一个属性子集,我需要将它绑定到一个下拉列表:

var locationDepts = (from u in users select new { u.RcNumber, u.RcName }).Distinct().ToList();

if(!locationDepts.Count.Equals(0))
{
    ddlRCListPerBuilding.DataSource = locationDepts;
    ddlRCListPerBuilding.DataValueField = "RcNumber";

    //Want to format display test "RCNumber - RcName"
    ddlRCListPerBuilding.DataTextField = string.Format("{0} - {1}", locationDepts.RcNumber, locationDepts.RcName);

    ddlRCListPerBuilding.DataBind();
}

我想将列表项显示文本格式化为匿名类型 RcNumber 和 RcName 的组合。如何访问匿名类型的属性以指示下拉列表项的文本格式?

4

3 回答 3

6

您可以在名为“Combined”的数据源中创建一个新属性

var locationDepts = (from u in users 
                    select new 
                    { 
                        u.RcNumber, 
                        Combined = u.RcNumber + " - " + u.RcName
                    }).Distinct().ToList();

if(locationDepts.Count > 0)
{
    ddlRCListPerBuilding.DataSource = locationDepts;
    ddlRCListPerBuilding.DataValueField = "RcNumber";
    ddlRCListPerBuilding.DataTextField = "Combined";
    ddlRCListPerBuilding.DataBind();
}
于 2012-04-10T20:14:28.690 回答
4

我只想更改匿名类型以包含已格式化的值:

var locationDepts = (from u in users select new { u.RcNumber, RcName = String.Format("{0} - {1}", u.RcNumber, u.RcName) }).Distinct().ToList();

if(!locationDepts.Count.Equals(0))
{
    ddlRCListPerBuilding.DataSource = locationDepts;
    ddlRCListPerBuilding.DataValueField = "RcNumber";

    ddlRCListPerBuilding.DataTextField = "RcName";

    ddlRCListPerBuilding.DataBind();
}
于 2012-04-10T20:14:41.770 回答
0

您可以使用视图模型

public class RcFields
{
    public int RcNumber { get; set; }
    public string RcName { get; set; } 
}

List<RcFields> locationDepts = (from u in users 
                                select new RcFields 
                                { 
                                   u.RcNumber, 
                                   u.RcName 
                                })
                                .Distinct()
                                .ToList();

然后

 ... locationDepts.RcName ..
于 2012-04-10T20:22:33.283 回答