2

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.

arie
  • 782
  • 3
  • 13
  • 31
  • Why not just use the .ToArray() method? – logix Aug 21 '17 at 14:25
  • 1
    Typically this would be done with LINQ's `.Select` - is that a viable solution? – Scott Aug 21 '17 at 14:26
  • 9
    `lst.Select(p => new PersonPrivate(convert(p.name), convert(p.lastname))).ToArray();` – Alexander Derck Aug 21 '17 at 14:26
  • Linq might make this easier: var privp = lst.Select(x => new(PersonPrivate(convert(x.name), convert(x.lastname))).ToArray(); – Kevin Cook Aug 21 '17 at 14:27
  • 2
    `ForEach` is almost always the wrong choice in my opinion (use `foreach` or `Select` depending on what you are trying to do). – crashmstr Aug 21 '17 at 14:27
  • Possible duplicate of [foreach loop vs. ForEach method - Differences?](https://stackoverflow.com/questions/33480820/foreach-loop-vs-foreach-method-differences) – Siva Gopal Aug 21 '17 at 14:36
  • @AlexanderDerck Your comment answers at least "is there a more elegant way to achieve this in C#?". So I think it would be appropriate to write it as an answer. I would upvote it. – Fildor Aug 21 '17 at 14:40

1 Answers1

5

Just use Select.

var arr = list
    .Select(p => new PersonPrivate(convert(p.name), convert(p.lastname)))
    .ToArray();
SavePerson(arr);
Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
Márton Balassa
  • 818
  • 7
  • 11