使用扩展方法,我们可以编写方便的LINQ操作符来解决通用问题。
我想听听您在System.Linq
命名空间中缺少哪些方法或重载以及您如何实现它们。
干净而优雅的实现,最好使用现有的方法。
使用扩展方法,我们可以编写方便的LINQ操作符来解决通用问题。
我想听听您在System.Linq
命名空间中缺少哪些方法或重载以及您如何实现它们。
干净而优雅的实现,最好使用现有的方法。
/// <summary>
/// Performs the specified action on each element of the IEnumerable.
/// </summary>
public static void ForEachAction<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (action == null || enumerable == null)
{
throw new ArgumentNullException();
}
foreach (var item in enumerable)
{
action.Invoke(item);
}
}
public static string Join<T>(this IEnumerable<T> items, string delimiter)
{
var result = new StringBuilder();
if (items != null && items.Any())
{
delimiter = delimiter ?? String.Empty;
foreach (var item in items)
{
result.Append(item);
result.Append(delimiter);
}
result.Length = result.Length - delimiter.Length;
}
return result.ToString();
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> enumerable, T item)
{
return enumerable.Concat(new[] { item });
}
public static IEnumerable<T> AppendIf<T>(this IEnumerable<T> enumerable, T item, Func<bool> predicate)
{
return predicate() ? enumerable.Append(item) : enumerable;
}