What is the most elegant way to loop through a List, do something on each element and create an array from those items?
These two solutions both serve the purpose, but are there pros/cons to using one over the other or is there a more elegant way to achieve this in C#?
Example 1:
public void SomeFunc(List<Person> lst)
{
PersonPrivate[] arr = new PersonPrivate[lst.Count];
int idx = 0;
lst.ForEach(x =>
{
PersonPrivate p = new PersonPrivate(convert(p.name), convert(p.lastname));
arr[idx] = p;
idx++;
}
SavePerson(arr);
}
Example 2:
public void SomeFunc(List<Person> lst)
{
PersonPrivate[] arr = new PersonPrivate[lst.Count];
for (int i = 0; i < lst.Count; i++)
{
PersonPrivate p = new PersonPrivate(convert(p.name), convert(p.lastname));
arr[i] = p;
}
SavePerson(arr);
}
EDIT: I don't believe this question is precisely the same as the one marked as duplicate. Although that one provides useful info too the comparison is not between for and foreach and not specific to creating an array from list.