How to key all values from NameValueCollection
as a single string,
Now I am using following method to get it:
public static string GetAllReasons(NameValueCollection valueCollection)
{
string _allValues = string.Empty;
foreach (var key in valueCollection.AllKeys)
_allValues += valueCollection.GetValues(key)[0] + System.Environment.NewLine;
return _allValues.TrimEnd(System.Environment.NewLine.ToCharArray());
}
Any simple solution using Linq
?
You could use the following:
string allValues = string.Join(System.Environment.NewLine, valueCollection.AllKeys.Select(key => valueCollection[key]));
It would depend on how you wanted to separate each value in your final string but I use a simple extension method to combine any IEnumerable<string>
to a value-separated string:
public static string ToValueSeparatedString(this IEnumerable<string> source, string separator)
{
if (source == null || source.Count() == 0)
{
return string.Empty;
}
return source
.DefaultIfEmpty()
.Aggregate((workingLine, next) => string.Concat(workingLine, separator, next));
}
As an example of how to use this with a NameValueCollection
:
NameValueCollection collection = new NameValueCollection();
collection.Add("test", "1");
collection.Add("test", "2");
collection.Add("test", "3");
// Produces a comma-separated string of "1,2,3" but you could use any
// separator you required
var result = collection.GetValues("test").ToValueSeparatedString(",");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With