简体   繁体   English

如何从NameValueCollection获取所有值作为单个字符串?

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

How to key all values from NameValueCollection as a single string, 如何将NameValueCollection中的所有值键入为单个字符串,
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 ? 任何使用Linq简单解决方案?

您可以使用以下内容:

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: 这将取决于你想如何分离最终字符串中的每个值,但我使用一个简单的扩展方法将任何IEnumerable<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一起使用的示例:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM