Solved

LINQ Concatenate Two Strings

Posted on 2015-01-02
5
232 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 74

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 32

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 32

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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now