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

2

5

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?

Flong answered 29/1, 2014 at 13:21 Comment(0)
I
8

You could use the following:

string allValues = string.Join(System.Environment.NewLine, valueCollection.AllKeys.Select(key => valueCollection[key]));
Initiatory answered 29/1, 2014 at 13:22 Comment(0)
E
1

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(",");
Enfold answered 29/1, 2014 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.