using System;
using System.Collections.Generic;
using System.Text;
namespace System.Linq
{
///
/// 通用比较器
///
///
///
public class CommonEqualityComparerHelper : IEqualityComparer
{
private Func keySelector;
public CommonEqualityComparerHelper(Func keySelector)
{
this.keySelector = keySelector;
}
public bool Equals(T x, T y)
{
return EqualityComparer.Default.Equals(keySelector(x), keySelector(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer.Default.GetHashCode(keySelector(obj));
}
}
///
/// 去重扩展
///
public static class DistinctExtensions
{
///
/// 去重
///
///
///
///
///
///
public static IEnumerable Distinct(this IEnumerable source, Func keySelector)
{
return source.Distinct(new CommonEqualityComparerHelper(keySelector));
}
///
/// 交集
///
///
///
///
///
///
///
public static IEnumerable Intersect(this IEnumerable source, IEnumerable target, Func keySelector)
{
return source.Intersect(target, new CommonEqualityComparerHelper(keySelector));
}
///
/// 差集
///
///
///
///
///
///
///
public static IEnumerable Except(this IEnumerable source, IEnumerable target, Func keySelector)
{
return source.Except(target, new CommonEqualityComparerHelper(keySelector));
}
}
///
/// 扩展
///
public static class QueryableExtensions
{
///
/// 带条件的Where
///
///
///
///
///
///
public static IEnumerable WhereIf(this IEnumerable query, bool condition, Func predicate)
{
return condition ? query.Where(predicate) : query;
}
///
/// 使 string的Join 变得丝滑
///
///
///
///
///
public static string JoinAsString(this IEnumerable query, string separator)
{
return string.Join(separator, query);
}
}
///
///
///
public static class StringExtensions
{
///
/// 安全的字符串截取
///
///
///
///
///
public static string SafeSubstring(this string input, int startIndex, int? length = null)
{
if (input == null)
{
return string.Empty;
}
if (startIndex < 0)
{
return string.Empty;
}
if (startIndex >= input.Length)
{
return string.Empty; // 起始索引超出范围,返回空字符串
}
int endIndex = length.HasValue ? Math.Min(startIndex + length.Value, input.Length) : input.Length;
return input.Substring(startIndex, endIndex - startIndex);
}
}
}