Solved

LINQ Concatenate Two Strings

Posted on 2015-01-02
5
240 Views
Last Modified: 2016-02-15
Hello all,

I need a clean way to handle this.   I have two 'possible' strings but either could be null.   I want to make a full string where it is "String1 - String2".  However if there is no String1 or String2 I want that value without the dash.   What is the cleanest way or one liner to do this in LINQ or doesn't have to be LINQ.

Thanks all
0
Comment
Question by:sbornstein2
5 Comments
 
LVL 44

Accepted Solution

by:
AndyAinscow earned 400 total points
ID: 40527957
No lINQ required:

            if (String.IsNullOrWhiteSpace(s1))
            {
                if (String.IsNullOrWhiteSpace(s2))
                    sResult = "";
                else
                    sResult = s2;
            }
            else
            {
                if (String.IsNullOrWhiteSpace(s2))
                    sResult = s1;
                else
                    sResult = s1 + " - " + s2;
            }

Open in new window


where s1 and s2 are the source strings and sResult is the concatenated string.  (It also copes with strings that are empty or just with spaces)
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 100 total points
ID: 40528024
I don't really recommend this approach because the anonymous collection is a tad un-readable, but another approach:

string string1 = "one";
string string2 = "";

string result = (new[] { string1, string2 }).Where(item => !string.IsNullOrWhiteSpace(item))
                                            .DefaultIfEmpty(string.Empty)
                                            .Aggregate((a, i) => a += " - " + i);  // a == "accumulator"; i == "iterator"

Open in new window

0
 
LVL 33

Expert Comment

by:it_saige
ID: 40528031
*No points*

Just another method using Andy's recommendation:
using System;

namespace EE_Q28589686
{
	class Program
	{
		static void Main(string[] args)
		{
			string str1 = "How now";
			string str2 = "brown cow";
			Console.WriteLine(Joined(str1, str2));
			Console.WriteLine();
			str1 = string.Empty;
			Console.WriteLine(Joined(str1, str2));
			Console.WriteLine();
			str1 = "How now";
			str2 = string.Empty;
			Console.WriteLine(Joined(str1, str2));
			Console.WriteLine();
			Console.ReadLine();
		}

		static string Joined(string s1, string s2)
		{
			return string.Format("{0}", string.IsNullOrEmpty(s1) ? string.IsNullOrEmpty(s2) ? string.Empty : s2 : string.Format("{0}{1}", s1, string.IsNullOrEmpty(s2) ? string.Empty : string.Format(" - {0}", s2)));
		}
	}
}

Open in new window

Produces the following results -Capture.JPGThis ofcourse, could be made into an extension method as such:
using System;

namespace EE_Q28589686
{
	class Program
	{
		static void Main(string[] args)
		{
			string str1 = "How now";
			string str2 = "brown cow";
			Console.WriteLine(str1.Joined(str2));
			Console.WriteLine();
			str1 = string.Empty;
			Console.WriteLine(str1.Joined(str2));
			Console.WriteLine();
			str1 = "How now";
			str2 = string.Empty;
			Console.WriteLine(str1.Joined(str2));
			Console.WriteLine();
			Console.ReadLine();
		}
	}

	static class Extensions
	{
		public static string Joined(this string s1, string s2)
		{
			return string.Format("{0}", string.IsNullOrEmpty(s1) ? string.IsNullOrEmpty(s2) ? string.Empty : s2 : string.Format("{0}{1}", s1, string.IsNullOrEmpty(s2) ? string.Empty : string.Format(" - {0}", s2)));
		}
	}
}

Open in new window

Which produces the same output as above.
However, I personallly would use Andy's version as such *over-usage* of a ternary method, mixed with string.Format calls, can lead to a little bit of confusion when just glancing at the method.

One liners, are not always, the best way to go.

-saige-
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40528032
I also echo Kaufmed's remarks.  ;)

-saige-
0
 

Author Closing Comment

by:sbornstein2
ID: 40528078
thanks all
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question