Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

LINQ Concatenate Two Strings

Posted on 2015-01-02
5
Medium Priority
?
293 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 45

Accepted Solution

by:
AndyAinscow earned 1600 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 400 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 34

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 34

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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

609 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