Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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. How do I access the properties of the anonymous type to indicate the format the text of the drop down list items?

like image 419
Michael Kniskern Avatar asked Dec 28 '22 02:12

Michael Kniskern


1 Answers

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();
}
like image 75
Magnus Avatar answered Jan 11 '23 22:01

Magnus