using System;
using System.Collections.Generic;
using System.Linq;
using System.Properties;
// ReSharper disable once CheckNamespace
namespace System
{
public static class EnumerableExtensions
{
///
/// 通过使用相应类型的默认相等比较器对序列的元素进行比较,以确定两个序列是否相等
///
/// 输入序列中的元素的类型
/// 一个用于比较 second 的
/// 要与第一个序列进行比较的
///
public static bool SequenceEqual_Nullable(this IEnumerable? first, IEnumerable? second)
{
if (first == null) return second == null;
if (second == null) return first == null;
return first.SequenceEqual(second);
}
///
/// 确定序列是否包含任何元素
///
/// source 的元素类型
/// 要检查是否为空的
/// 如果源序列包含任何元素,则为 ;否则为
public static bool Any_Nullable(this IEnumerable? source)
{
if (source == null) return false;
return source.Any();
}
///
/// 确定序列是否包含任何元素(带条件)
///
///
///
///
///
public static bool Any_Nullable(this IEnumerable? source, Func predicate)
{
if (source == null) return false;
return source.Any(predicate);
}
public static Dictionary ReverseKeyValue(this IEnumerable> source) where TKey : notnull
=> source.ToDictionary(k => k.Value, v => v.Key);
///
public static void AddRange(this IList ts, IEnumerable collection)
{
if (ts is List list)
{
list.AddRange(collection);
}
else
{
if (ts.IsReadOnly) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection);
var c = collection == ts ? collection.ToArray() : collection;
foreach (var item in c)
{
ts.Add(item);
}
}
}
public static IEnumerable Distinct(this IEnumerable source, Func keySelector)
{
var set = new HashSet(EqualityComparer.Default);
foreach (var item in source)
{
var key = keySelector(item);
if (set.Add(key)) yield return item;
}
}
public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)
{
HashSet seenKeys = new HashSet();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
///
/// コレクションを展開し、メンバーの文字列表現を指定した区切り文字で連結した文字列を返します。
///
/// コレクションに含まれる任意の型。
/// 対象のコレクション。
/// セパレーターとして使用する文字列。
/// コレクションの文字列表現を展開し、指定したセパレーターで連結した文字列。
public static string ToString(this IEnumerable source, string separator) => string.Join(separator, source);
///
/// コレクションを展開し、メンバーの文字列表現を指定した区切り文字で連結した文字列を返します。
///
/// コレクションに含まれる任意の型。
/// 対象のコレクション。
/// セパレーターとして使用する文字列。
/// コレクションの文字列表現を展開し、指定したセパレーターで連結した文字列。
public static string ToString(this IEnumerable source, char separator) => string.Join(separator, source);
#if DEBUG
///
/// シーケンスが null でなく、1 つ以上の要素を含んでいるかどうかを確認します。
///
[Obsolete("use Any_Nullable()", true)]
public static bool HasItems(this IEnumerable? source)
{
return source != null && source.Any();
}
#endif
}
}