none
How to combine string and array of string into one array? RRS feed

  • Question

  • i want to combine string and array of string into new string array. Below is my code which is working however i would like to simplify this if possible

    Note that .each is the extension method i have on IEnumerable

    public string[] GetErrors(IEnumerable<MyEntity> entity)
    {
    var errors = new List<string>();
    errors.Add("Below are the errors:");
    entity.Each(x => errors.Add(x.Message));
    return errors;
    }


    Tuesday, June 2, 2015 11:21 PM

Answers

  • Maybe you could reduce it a bit more and then call ToArray on errors.

    var errors = new List<string>{ "Below are the errors:" };
    return errors.Concat(entity.Select(x => x.Message)).ToArray();

    • Marked as answer by lax4u Wednesday, June 3, 2015 6:17 AM
    Wednesday, June 3, 2015 1:53 AM

All replies

  • Perhaps the best way to simplify this is to maintain the data in a List<string> and only convert it to an array (with the ToArray method) when you have to (and perhaps avoid the need to ever convert it to an array).
    Tuesday, June 2, 2015 11:32 PM
  • Maybe you could reduce it a bit more and then call ToArray on errors.

    var errors = new List<string>{ "Below are the errors:" };
    return errors.Concat(entity.Select(x => x.Message)).ToArray();

    • Marked as answer by lax4u Wednesday, June 3, 2015 6:17 AM
    Wednesday, June 3, 2015 1:53 AM