2021-02-18 11:06:02 +01:00
|
|
|
|
// Copyright (c) Umbraco.
|
|
|
|
|
|
// See LICENSE for more details.
|
|
|
|
|
|
|
2018-06-29 19:52:40 +02:00
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Collections.Specialized;
|
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
|
2021-02-18 11:06:02 +01:00
|
|
|
|
namespace Umbraco.Extensions
|
2018-06-29 19:52:40 +02:00
|
|
|
|
{
|
2019-11-15 11:07:37 +01:00
|
|
|
|
public static class NameValueCollectionExtensions
|
2018-06-29 19:52:40 +02:00
|
|
|
|
{
|
2022-01-11 11:47:31 +01:00
|
|
|
|
public static IEnumerable<KeyValuePair<string?, string?>> AsEnumerable(this NameValueCollection nvc)
|
2018-06-29 19:52:40 +02:00
|
|
|
|
{
|
2022-01-11 11:47:31 +01:00
|
|
|
|
foreach (string? key in nvc.AllKeys)
|
2018-06-29 19:52:40 +02:00
|
|
|
|
{
|
2022-01-11 11:47:31 +01:00
|
|
|
|
yield return new KeyValuePair<string?, string?>(key, nvc[key]);
|
2018-06-29 19:52:40 +02:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public static bool ContainsKey(this NameValueCollection collection, string key)
|
|
|
|
|
|
{
|
|
|
|
|
|
return collection.Keys.Cast<object>().Any(k => (string) k == key);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-01-11 11:47:31 +01:00
|
|
|
|
public static T? GetValue<T>(this NameValueCollection collection, string key, T defaultIfNotFound)
|
2018-06-29 19:52:40 +02:00
|
|
|
|
{
|
|
|
|
|
|
if (collection.ContainsKey(key) == false)
|
|
|
|
|
|
{
|
|
|
|
|
|
return defaultIfNotFound;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var val = collection[key];
|
|
|
|
|
|
if (val == null)
|
|
|
|
|
|
{
|
|
|
|
|
|
return defaultIfNotFound;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var result = val.TryConvertTo<T>();
|
|
|
|
|
|
|
2022-02-09 13:24:35 +01:00
|
|
|
|
return result.Success ? result.Result : defaultIfNotFound;
|
2018-06-29 19:52:40 +02:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|