سؤال

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(",");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top