Convert List<Enum> to List<string> - c#

I have a list of enum values:
public static readonly List<NotifyBy> SupportedNotificationMethods = new List<NotifyBy> {
NotifyBy.Email, NotifyBy.HandHold };
I would like to output it as a comma separated list. (EG: "Email, Handhold")
What is the cleanest way of doing this?

Perhaps this:
var str = String.Join(", ", SupportedNotificationMethods.Select(s => s.ToString()));
You can read more about the String.Join method at MSDN. Older versions of String.Join don't have an overload that takes an IEnumerable. In that case just call ToArray() after select.

you can use linq:
string.Join(", ", SupportedNotificationMethods.Select(e => e.ToString());

String.Join(", ", SupportedNotificationMethods.Select(e => e.ToString()).ToArray());

Related

How to concatenate two List<string> to a single string using Aggregate method

I have two lists of strings. My manager's requirement is to concatenate both lists and output as a string using LINQ.
List<string> upper = new List<string> { "A", "B", "C" };
List<string> lower = new List<string> { "a", "b", "c" };
The output should be something as below:
//string output = "A:a,B:b,C:c"
And to achieve this, I need to use LINQ Aggregate method or other extension methods available. Please help
You are looking for the method Zip and maybe combined with string.Join
Console.WriteLine(string.Join(",", upper.Zip(lower, (u, l) => u + ":" + l)));
This outputs: A:a,B:b,C:c
You need Zip method not Aggregate:
If you want the result as a List of String:
List<string> result = upper.Zip(lower, (first, second) => first + ":" + second).ToList();
If you want the result as a string you can either use String.Join method like this:
string output = string.Join(",", result);
Or Aggregate method as you are looking for like this:
string output = result.Aggregate((f, s) => f + "," + s);
Use Enumerable.Zip:
var results = upper.Zip(lower, (up, low) => $"{up}:{low}");
Now to convert it into a single string:
string output = string.Join(",", results);

Pair values from two lists

I have two lists with me as per the following example.
List<string> words = new List<string>() {"V","H","M" };
List<int> numbers = new List<int>() {10,20,30 };
I need to pair the values of these two lists so that my output needs to be exactly like the following text.
Desired output : V10 H20 M30
You could use Zip method for that.
You can try the following:
String.Join(" ", words.Zip(numbers, (first, second) => first + second))
Try using Zip:
var result = words
.Zip(numbers, (w, n) => $"{w}{n}");
Console.Write(string.Join(" ", result));
I'm a bit late to the party but here's a very simple way of doing it without Zip: (x = item, y = index)
var mergedList = words.Select((x, y) => $"{x}{numbers.ElementAt(y)}");

How to intertwine two strings or arrays, possibly with String.Join()

I have the following string arrays:
var myArray1 = new string[] {"A", "B", "C"};
var myArray2 = new string[] {"t1", "t2"};
I would like to be able to produce a final string that looks like this:
var myFinalString = "t1.A, t2.A, t1.B, t2.B, t1.C, t2.C";
I know I can iterate through each element of the array and build the string manually. However, I'd like to know if there's a better way. I tried to figure out how to make String.Join() method work, but couldn't :-(.
I don't know that any direct method exists, but this one-liner
return
from a in myArray
from b in tTerms
select string.Format("{0}.{1}", b, a)
should do it.
This works:
var query = from x in new[]{"A", "B", "C"}
from y in new[]{"t1", "t2"}
select y + "." + x;
var result = string.Join(", ", query.ToArray());
The term for such sequence is "Cartesian Product".
Here is long blog by Eric Lippert on it Computing a Cartesian Product with LINQ
As it is already shown in other answers sequence of tuples can be obtained with following code and than aggregated (using Join in case of string, or Aggregate for other type of result) to produce your final string:
var product =
from first in s1
from second in s2
select new[] { first, second };
var result String.Join(", ",
product.Select(p => String.Format("{0}.{1}", p.first, p.second));
If the two sequences are of the same length, you could probably put Enumerable.Zip to work for you.
var myFinalString = myArray.Zip(mySecondArray, (f, s) => f + "." + s);

string.Join throws OutOfMemory Exception

I have a list of strings and I want to join them with " "(space) between them, so I use the string.Join method:
foreach (var line in lines)
{
var strings = lines.Where(l => l.Code == line.Code).Select(l => l.Data);
var original = string.Join(" ", strings);
}
Data looks something like this: "123456789, 987654321, 32132, 7873892 ..."
But I get an OutOfMemoryException. Why? each string is approximatly 100-150 characters and there are 5-10 strings in the list.
Is there a better way then the string.Join?
Try this (and let us know if you get the same error):
lines.GroupBy(l => l.Code).Select(l => string.Join(" ", l.Select (x => x.Data)));
foreach (var line in lines.GroupBy(p=>p.Code))
{
var original = string.Join(" ", line.Select(p=>p.Data));
}
The StringBuild() class can join strings and isn't immutable.
Here's an MSDN article talking about immutable string vs how StringBuilder works.
http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

One line LINQ to flatten string[] to a string?

I came up with the foreach below but I am hoping this can be accomplished in one line.. maybe linq? Any ideas would be appreciated.
foreach (string item in decoder.AllKeys)
{
message += String.Format("{0}: {1} ;", item, decoder[item]);
}
var message = string.Join(
";",
decoder.AllKeys
.Select(x => string.Format("{0}: {1} ", x, decoder[item]))
.ToArray()
);
The String class from BCL already supports this. Here is a one liner to achieve this using String class. I would always use the BCL operation if it's available there considering the MS guys would have already taken the pain to optimize such a crucial class.
String.Join(";", decoder.AllKeys);
Here is the link to the MSDN for all the variants of this method - http://goo.gl/kmwfYt
If you're in .NET 4.0, you can use this:
string message = string.Join(" ;", decoder.AllKeys
.Select(k => string.Format("{0}: {1}", k, decoder[k]));
If you're not on .NET 4.0 yet, you need to convert the collection to an array:
string message = string.Join(" ;", decoder.AllKeys
.Select(k => string.Format("{0}: {1}", k, decoder[k]).ToArray());
This should work.
decoder.AllKeys.Aggregate("", (current, item) => current + String.Format("{0}: {1} ;", item, decoder[item]));
IEnumerable<string> query =
from KeyValuePair<string, string> kvp in decoder
select String.Format("{0}: {1} ;", kvp.Key, kvp.Value);
string result = string.Join(null, query);
If you already have a Join extension method on IEnumerable like I have:
public static string Join(this IEnumerable<string> values, string separator)
{
return string.Join(separator, values);
}
then the rest is just a one-liner:
decoder.AllKeys.Select(item => String.Format("{0}: {1}", item, decoder[item])).Join(";");
Note that if you're not using .NET 4, then you can replace the implementation of the extension method to whatever works for your version.
EDIT:
Even better, create the following extension method:
public static string Join(this IEnumerable<string> values, string separator, Func<string, string> selector)
{
return string.Join(separator, values.Select(selector));
}
and call it as follows:
decoder.AllKeys.Join(";", item => String.Format("{0}: {1}", item, decoder[item]));
you won't get more one-line than that, other than putting an extension method on NameValueCollection, or whatever decoder is :)

Categories