Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all values as a single string from NameValueCollection?

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?

like image 669
Ankush Madankar Avatar asked Jan 29 '14 13:01

Ankush Madankar


2 Answers

You could use the following:

string allValues = string.Join(System.Environment.NewLine, valueCollection.AllKeys.Select(key => valueCollection[key]));
like image 179
Paweł Bejger Avatar answered Nov 15 '22 07:11

Paweł Bejger


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(",");
like image 30
Peter Monks Avatar answered Nov 15 '22 09:11

Peter Monks