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.

7
  • Why not just use the .ToArray() method? Commented Aug 21, 2017 at 14:25
  • 1
    Typically this would be done with LINQ's .Select - is that a viable solution? Commented Aug 21, 2017 at 14:26
  • 9
    lst.Select(p => new PersonPrivate(convert(p.name), convert(p.lastname))).ToArray(); Commented Aug 21, 2017 at 14:26
  • Linq might make this easier: var privp = lst.Select(x => new(PersonPrivate(convert(x.name), convert(x.lastname))).ToArray(); Commented Aug 21, 2017 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). Commented Aug 21, 2017 at 14:27

1 Answer 1

5

Just use Select.

var arr = list
    .Select(p => new PersonPrivate(convert(p.name), convert(p.lastname)))
    .ToArray();
SavePerson(arr);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.