简体   繁体   English

访问匿名类型集合中的属性 - C#

[英]Access properties in anonymous type collection - C#

In the source code below, I am selecting a subset of properties from the users collection and I need to bind it to a drop down list:在下面的源代码中,我从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();
}

I want to format the list item display text as a combination of the anonymous type RcNumber and RcName.我想将列表项显示文本格式化为匿名类型 RcNumber 和 RcName 的组合。 How do I access the properties of the anonymous type to indicate the format the text of the drop down list items?如何访问匿名类型的属性以指示下拉列表项文本的格式?

You can create a new property in the data-source called "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();
}

I would just change the anonymous type to include the already-formatted value:我只想更改匿名类型以包含已格式化的值:

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();
}

You could use a view model您可以使用视图 model

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();

then然后

 ... locationDepts.RcName ..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM