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
Solved

LINQ Concatenate Two Strings

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

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 article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

860 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