?
Solved

LINQ Concatenate Two Strings

Posted on 2015-01-02
5
Medium Priority
?
277 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 44

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

771 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