Skye
Skye

Reputation: 19

Var array to list box

So on my last post, C# Json - to - Array I asked how to get the two values to a array. But I was given a var, how do I get those variables in a list box "main_Listbox"?

Upvotes: 1

Views: 325

Answers (3)

Christian Phillips
Christian Phillips

Reputation: 18769

In the answer I gave you in the previous question, I have used the following with a var

var totalBonusUsers = (from user in data.users
                                   let tot = user.bonus.GetTotalBonus()
                                   select new TotalUserBonus {username = user.username, totalBonus = tot}).ToList()
                                                                                                          .OrderByDescending
                (u => u.totalBonus).ToList();

var is actually = List<TotalUserBonus> in this instance.

main_Listbox.DataSource = totalBonusUsers;
main_Listbox.DataTextField = "username";
main_Listbox.DataValueField = "totalBonus";
main_Listbox.DataBind();

Upvotes: 0

Zignd
Zignd

Reputation: 7025

Basically to add values of an array or any collection you can use the foreach statement that allows you to iterate over all the elements of a collection that implements the IEnumerable interface. For example:

foreach (var user in listOfUsers)
{
    listBox.Items.Add(String.Format("{0} {1} {2}", user.id, user.pass, user.status.ToString());
}

Considering that listOfUsers is of type List<User> and the User class is like that:

class User
{
    public string id;
    public string pass;
    public int status;
}

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65077

Anything declared as var in code is implicitly typed. This means the following:

var s = "Hello World!"; // This is compiled as a string
var i = 10; // This is compiled as an integer
var list = new List<string>(); // This is compiled as a List of strings
var arr = new byte[255]; // This is compiled as a byte array.

Your linked post appears to show that your variable is assigned from a json serializer. This means it will be a string.

There is also another assignment in the other answer that would be a List<User>.

Upvotes: 1

Related Questions