在下面的源代码中,我从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的组合。如何访问匿名类型的属性以指示下拉列表项的文本格式?
答案 0 :(得分: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();
}
答案 1 :(得分: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();
}
答案 2 :(得分: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 ..