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

5

如何将NameValueCollection中的所有值作为一个单一字符串键入,
现在我使用以下方法来获取它:

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());
}

有没有使用Linq的简单解决方法?

2个回答

8
您可以使用以下内容:
string allValues = string.Join(System.Environment.NewLine, valueCollection.AllKeys.Select(key => valueCollection[key]));

1

这取决于您希望如何在最终字符串中分隔每个值,但我使用一个简单的扩展方法将任何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));
}

作为如何使用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(",");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接