Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Good, bad or just a bit ugly : string[] RemoveEmpties(string[] source)

I'm building up a bunch of conditions for an SqlWhereClause and there is an option to AND the various condition or to OR them.

I have a few function to build the conditions, but when I get around to putting them all together some of them are blank so when I String.Join them I get extra ANDs/ORs in my final statement.

This eventualy led me to the RemoveEmpties function, which takes a array of strings and returns an array that contains only the non-null non-empty ones.

 

private string JoinSQLFragments(string joiner,params string[] fragments)

            {

                  return String.Join(joiner,RemoveEmpties(fragments));

            }

            private string[] RemoveEmpties(string[] source)

            {

                  ArrayList list = new ArrayList(); // :(

                  foreach(string item in source)

                  {

                        if(item!=null && item.Length > 0)

                        {

                              list.Add(item);

                        }

                  }

                  return (string[]) list.ToArray(typeof(string));

            }

I call these from something like the following, each of the BuildX methods can return a blank string.

JoinSQLFragments(" OR ",BuildMonthRangeCriteria("FieldA",criteriaA),BuildKeywordCriteria(keyword));

Any helpful thoughts or beauty tips ;) will be appreciated

5 Comments

  • Personally I'd go for a different joining method, using a stringbuilder, pass through the fragments list doing AppendFormat on each one that wasn't null...

  • Annother thanks :)



    I grabbed the chance to create the function JoinStrings(string joiner,params string[] fragments)

    , then I ended up with nulls so I added the cruft:





    Would you use that approach to avoid the cruft with the ArrayList or to avoid the String.Join?



    Would .Append maybe be better than AppendFormat?

  • To avoid the casting and Arraylist stage - since it really seems pretty unnecessary. Essentially (and there's every chance I'm wrong here as my reflector can't see the method right now!) I believe that string.Join just uses a StringBuilder internally to perform the join. It should be that the version I suggested is of equivalent performance (or very close) to the original string.Join yet avoids the overhead your RemoveEmpties method introduces.

  • Oh, StringBuilder.Append would of course be faster than AppendFormat:-)

  • From ILDASM, internalcall...



    .method public hidebysig static string Join(string separator,string[] 'value',int32 startIndex,int32 count) cil managed internalcall

    {

    } // end of method String::Join

Comments have been disabled for this content.