'How to loop to add items up to a quantity
I'm trying to make a loop to add 10 items but only add one with the number 10.
List<Contact> listContact;
for (int cuantidade = 0; cuantidade < 10; cuantidade++)
{
listContact = new List<Contact>(cuantidade)
{
new Contact()
{
Name = cuantidade.ToString(),
Number = cuantidade.ToString(),
},
};
}
this.listBoxNames.ItemsSource = listContact;
What am I doing wrong?
Solution 1:[1]
Try this:
var contactList= new List<Contact>();
for (int cuantidade = 0; cuantidade < 10; cuantidade++)
{
contactList.Add(new Contact
{
Name = cuantidade.ToString(),
Number = cuantidade.ToString(),
});
}
this.listBoxNames.ItemsSource = contactList;
Solution 2:[2]
You need to set the list before the loop. With your current code, at every iteration the list is redefined and resets...
Solution 3:[3]
Here is an alternate example pair using Linq
- The first just gets 10
- The second starts at one point (13) and then gets the next 7
I used a number generator just for the example but it could be any source.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Generate a sequence of integers from 9 to 50
IEnumerable<int> quanityNumbers = Enumerable.Range(9, 50);
// just take the first 10:
List<Contact> contacts = quanityNumbers
.Take(10)
.Select(a => new Contact()
{
Name = a.ToString(),
Number = a.ToString()
}).ToList();
Console.WriteLine($"Hello World contacts has {contacts.Count} items");
foreach (var c in contacts)
{
Console.WriteLine($"contacts has Name: {c.Name} with Number: {c.Number}");
}
//Start at some point and take 7 from there:
List<Contact> contactsFromTo = quanityNumbers
.Skip(13)
.Take(7)
.Select(a => new Contact()
{
Name = a.ToString(),
Number = a.ToString()
}).ToList();
Console.WriteLine($"Hello World contactsFromTo has {contactsFromTo.Count} items");
foreach (var c in contactsFromTo)
{
Console.WriteLine($"contactsFromTo has Name: {c.Name} with Number: {c.Number}");
}
}
public class Contact
{
public string Name { get; set; }
public string Number { get; set; }
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew Hillier |
| Solution 2 | Marcel Gosselin |
| Solution 3 | Mark Schultheiss |
