public static class IEnurambleExtension { public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> keys = new HashSet<TKey>(); foreach (TSource element in source) if (keys.Add(keySelector(element))) yield return element; } public static IEnumerable<int> DistinctByReturnIndexes<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> keys = new HashSet<TKey>(); int i = 0; foreach (TSource element in source) { if (!keys.Add(keySelector(element))) yield return i; i++; } } public static int FirstContainsWithIndex<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate) { int i = 0; foreach (TSource element in source) { if (predicate(element)) return i; i++; } return -1; } public static IEnumerable<int> ContainsReturnIndexes<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate) { int i = 0; foreach (TSource element in source) { if (predicate(element)) yield return i; i++; } } public static void Print<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { foreach (TSource element in source) Console.WriteLine(keySelector(element)); } }
本文详细介绍了在C#中如何使用LINQ扩展方法进行数据操作,包括DistinctBy用于去除重复项,FirstContainsWithIndex查找首个符合条件元素的索引,ContainsReturnIndexes返回所有符合条件元素的索引,以及Print方法用于打印集合中的元素。这些方法通过提供额外的参数如keySelector和predicate,增强了LINQ的功能性和灵活性。
1443

被折叠的 条评论
为什么被折叠?



