Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 595383
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T16:03:21+00:00 2026-05-13T16:03:21+00:00

This problem has bugged me for years, and I always feel like I’m coming

  • 0

This problem has bugged me for years, and I always feel like I’m coming up with a hack when there’s a much better solution. The issue at hand occurs when you want to do something to all items in a list and then add something inbetween those items. In short, I want to:

  • Do something to every item in the list.
  • Do something else to all but the last item in the list (in effect, do something “inbetween” the items in the list).

For example, let’s say I have a class called Equation:

public class Equation
{
    public string LeftSide { get; set; }
    public string Operator { get; set; }
    public string RightSide { get; set; }
}

I want to iterate over a list of Equations and return a string that formats these items together; something like the following:

public string FormatEquationList(List<Equation> listEquations)
{
    string output = string.Empty;
    foreach (Equation e in listEquations)
    {
        //format the Equation
        string equation = "(" + e.LeftSide + e.Operator + e.RightSide + ")";

        //format the "inbetween" part
        string inbetween = " and ";

        //concatenate the Equation and "inbetween" part to the output
        output += equation + inbetween;
    }
    return ouput;
}

The problem with the above code is that it is going to include and at the end of the returned string. I know that I could hack some code together, replace the foreach with a for loop, and add the inbetween element only if it’s not the last item; but this seems like a hack.

Is there a standard methodology for how to deal with this type of problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T16:03:22+00:00Added an answer on May 13, 2026 at 4:03 pm

    You basically have a few different strategies for dealing with this kind problem:

    1. Process the first (or last) item outside of the loop.
    2. Perform the work and then “undo” the extraneous step.
    3. Detect that your’re processing the first or last item inside the loop.
    4. Use a higher-level abstraction that allows you to avoid the situation.

    Any of these options can be a legitimate way to implement a “between the items” style of algorithm. Which one you choose depends on things like:

    • which style you like
    • how expensive “undoing work” is
    • how expensive each “join” step is
    • whether there are any side effects

    Amongst other things. For the specific case of string, I personally prefer using string.Join(), as I find it illustrates the intent most clearly. Also, in the case of strings, if you aren’t using string.Join(), you should try to use StringBuilder to avoid creating too many temporary strings (a consequence of strings being immutable in .Net).

    Using string concatentation as the example, the different options break down into examples as follows. (For simplicity, assume Equation has ToString() as: "(" + LeftSide + Operator + RightSide + ")"

    public string FormatEquation( IEnumerable<Equation> listEquations )
    {
        StringBuilder sb = new StringBuilder();
    
        if( listEquations.Count > 0 )
            sb.Append( listEquations[0].ToString() );
        for( int i = 1; i < listEquations.Count; i++ )
            sb.Append( " and " + listEquations[i].ToString() );
        return sb.ToString();
    }
    

    The second option looks like:

    public string FormatEquation( IEnumerable<Equation> listEquations )
    {
        StringBuilder sb = new StringBuilder();
        const string separator = " and ";
        foreach( var eq in listEquations )
            sb.Append( eq.ToString() + separator );
        if( listEquations.Count > 1 )
            sb.Remove( sb.Length, separator.Length );
    }
    

    The third would look something like:

    public string FormatEquation( IEnumerable<Equation> listEquations )
    {
        StringBuilder sb = new StringBuilder();
        const string separator = " and ";
        foreach( var eq in listEquations )
        {
            sb.Append( eq.ToString() );
            if( index == list.Equations.Count-1 )
                break;
            sb.Append( separator );
        }
    }
    

    The last option can take multiple forms in .NET, using either String.Join or Linq:

    public string FormatEquation( IEnumerable<Equation> listEquations )
    {
        return string.Join( " and ", listEquations.Select( eq => eq.ToString() ).ToArray() );
    }
    

    or:

    public string FormatEquation( IEnumerable<Equation> listEquations ) 
    {
        return listEquations.Aggregate((a, b) => a.ToString() + " and " + b.ToString() );
    }
    

    Personally, I avoid using Aggregate() for string concatenation because it results in many intermediate, discarded strings. It’s also not the most obvious way to “join” a bunch of results together – it’s primarily geared for computing a “scalar” results from a collection in some arbitrary, caller-defined fashion.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This problem has bugged me so many times and i have now decided to
Premise This problem has a known solution (shown below actually), I'm just wondering if
UPDATE It looks like this problem has been quietly fixed in iOS 4.3. Up
This has bugged me for years but I cannot find anything about it in
This problem has been getting at me for a while now. Is there an
This problem has been driving me nuts all day and there has to be
I have a problem and I would like to apologize, if this problem has
OK this is a problem that has bugged be for ages. I am looking
This problem has been bugging me for a long time. For example, the code
This problem has happened to me twice.Both times during programming with Borland C++.when i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.