0

The method below returns only the first object in the array.

public string PRINT_CRATE()
{

    foreach (var soda in sodaCans)
    {
        if (soda != null)
        {
            return string.Join(Environment.NewLine, soda);                    
        }
        else
        {
            return ("Empty spot");
        }
    }

    return null;
}

It works fine except from that I want it to "group up" all the objects and return them. As it is now, only the first object get's returned.

What is the best approach for this?

5
  • 1
    Look into string concatenation and/or the StringBuilder. Commented May 20, 2015 at 23:20
  • What is sodaCans? string[]? List<string>? Commented May 20, 2015 at 23:20
  • In any event, you're using String.Join on a single element of the collection, when in reality you just need to pass the collection into String.Join - String.Join(Environment.NewLine, sodaCans);. String.Join Commented May 20, 2015 at 23:23
  • Final comment - it returns the first object because you tell it to. return string.Join(Environment.NewLine, soda); will exit the method the first time a non-null element is found. The next time you enter the method, it will start over. Commented May 20, 2015 at 23:25
  • Thanks a lot for the effort! Commented May 20, 2015 at 23:40

2 Answers 2

4

Probably the simplest thing to do what you're asking for is a Linq query:

return string.Join(Environment.NewLine, sodaCans.Select(x => x ?? "EmptySpot"));   

The .Select method allows you to transform each element, and here I'm using the null coalescing operator ?? to replace null values with "EmptySpot".

Sign up to request clarification or add additional context in comments.

Comments

1

if you want to return a single string with all the data put into it, you are probably looking for something like that:

public string PrintCrate()
{
    string rv = "";
    foreach (var soda in sodaCans)
    {
        if (soda != null)
        {
            rv += "\n" + soda;                    
        }
    }

    return rv;
}

EDIT: According to the comments, my solution was sub-optimal.

I'd like to point out, that Erik's answer is probably the best solution. It is short, correctly handles the newlines, and outputs the "Empty Spot" entries as the OP has probably wanted.

Out of educational value, I'll include a version with StringBuilder and manual enumeration that is comparable with Erik's answer in that it is close to the implementation of string.Join():

public string PrintCrate()
{
    using (var enumerator = sodaCans.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return null
        var stringBuilder = new StringBuilder();
        stringBuilder.Append(enumerator.Current ?? "EmptySpot");
        while (enumerator.MoveNext())
        {
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.Append(enumerator.Current ?? "EmptySpot");
        }
        return StringBuilder.ToString();
    }
}

5 Comments

String.Join or even StringBuilder would be better than +=.
Thanks a lot! It's so obvious when I see it. But yet I'm till too fresh to figure it out. Thanks again mate =)
@Tim For someone who starts with this kind of coding, I think it is more comprehensible to use simple strings. And besides, I'm pretty sure the compiler or jit will use the StringBuilder behind the scenes, on such obvious cases.
@justme no, the compiler/jit will not rewrite your code to use a stringbuilder. Also note that your code puts a newline at the start of the string, where string.join wouldn't.
@justme - Given that OP had String.Join in their question, I think it would have been better to show them how to properly use it to achieve the results they wanted, along with an explanation as to why String.Join or StringBuilder would be a better choice than +=, but that's just me.

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.