Files
Umbraco-CMS/src/Umbraco.Core/Extensions/NameValueCollectionExtensions.cs

44 lines
1.2 KiB
C#
Raw Normal View History

// 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;
namespace Umbraco.Extensions
2018-06-29 19:52:40 +02: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
}
}
}