Какой ваш любимый оператор LINQ to Objects, который не встроен?
С помощью методов расширения мы можем написать удобные операторы LINQ, которые решают общие проблемы.
Я хочу узнать, какие методы или перегрузки вам не хватает в пространстве имен System.Linq
и как вы их реализовали.
Предпочтительны чистые и элегантные реализации, возможно, используя существующие методы.
Ответы
Ответ 1
Добавление и предварительная подготовка
/// <summary>Adds a single element to the end of an IEnumerable.</summary>
/// <typeparam name="T">Type of enumerable to return.</typeparam>
/// <returns>IEnumerable containing all the input elements, followed by the
/// specified additional element.</returns>
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T element)
{
if (source == null)
throw new ArgumentNullException("source");
return concatIterator(element, source, false);
}
/// <summary>Adds a single element to the start of an IEnumerable.</summary>
/// <typeparam name="T">Type of enumerable to return.</typeparam>
/// <returns>IEnumerable containing the specified additional element, followed by
/// all the input elements.</returns>
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> tail, T head)
{
if (tail == null)
throw new ArgumentNullException("tail");
return concatIterator(head, tail, true);
}
private static IEnumerable<T> concatIterator<T>(T extraElement,
IEnumerable<T> source, bool insertAtStart)
{
if (insertAtStart)
yield return extraElement;
foreach (var e in source)
yield return e;
if (!insertAtStart)
yield return extraElement;
}
Ответ 2
Я удивлен, что никто еще не упомянул MoreLINQ project. Он был запущен Jon Skeet и заработал несколько разработчиков на этом пути. На странице проекта:
LINQ to Objects пропускает несколько желательные функции.
Этот проект улучшит LINQ до Объекты с дополнительными методами, в способ, который держится в духе LINQ.
Взгляните на страницу Обзор операторов для списка реализованных операторов.
Это, безусловно, хороший способ узнать из чистого и элегантного исходного кода.
Ответ 3
Каждый
Ничто для пуристов, но чертовски полезно!
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var i in items)
action(i);
}
Ответ 4
ToQueue и ToStack
/// <summary>Creates a <see cref="Queue<T>"/> from an enumerable
/// collection.</summary>
public static Queue<T> ToQueue<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
return new Queue<T>(source);
}
/// <summary>Creates a <see cref="Stack<T>"/> from an enumerable
/// collection.</summary>
public static Stack<T> ToStack<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
return new Stack<T>(source);
}
Ответ 5
IsEmpty
public static bool IsEmpty<T>(this IEnumerable<T> source)
{
return !source.Any();
}
Ответ 6
In и NotIn
С# эквиваленты двух других хорошо известных конструкций SQL
/// <summary>
/// Determines if the source value is contained in the list of possible values.
/// </summary>
/// <typeparam name="T">The type of the objects</typeparam>
/// <param name="value">The source value</param>
/// <param name="values">The list of possible values</param>
/// <returns>
/// <c>true</c> if the source value matches at least one of the possible values; otherwise, <c>false</c>.
/// </returns>
public static bool In<T>(this T value, params T[] values)
{
if (values == null)
return false;
if (values.Contains<T>(value))
return true;
return false;
}
/// <summary>
/// Determines if the source value is contained in the list of possible values.
/// </summary>
/// <typeparam name="T">The type of the objects</typeparam>
/// <param name="value">The source value</param>
/// <param name="values">The list of possible values</param>
/// <returns>
/// <c>true</c> if the source value matches at least one of the possible values; otherwise, <c>false</c>.
/// </returns>
public static bool In<T>(this T value, IEnumerable<T> values)
{
if (values == null)
return false;
if (values.Contains<T>(value))
return true;
return false;
}
/// <summary>
/// Determines if the source value is not contained in the list of possible values.
/// </summary>
/// <typeparam name="T">The type of the objects</typeparam>
/// <param name="value">The source value</param>
/// <param name="values">The list of possible values</param>
/// <returns>
/// <c>false</c> if the source value matches at least one of the possible values; otherwise, <c>true</c>.
/// </returns>
public static bool NotIn<T>(this T value, params T[] values)
{
return In(value, values) == false;
}
/// <summary>
/// Determines if the source value is not contained in the list of possible values.
/// </summary>
/// <typeparam name="T">The type of the objects</typeparam>
/// <param name="value">The source value</param>
/// <param name="values">The list of possible values</param>
/// <returns>
/// <c>false</c> if the source value matches at least one of the possible values; otherwise, <c>true</c>.
/// </returns>
public static bool NotIn<T>(this T value, IEnumerable<T> values)
{
return In(value, values) == false;
}
Ответ 7
JoinString
В основном то же самое, что и string.Join
, но:
-
с возможностью использовать его в любой коллекции, а не только для набора строк (вызовы ToString
для каждого элемента)
-
с возможностью добавления префикса и суффикса для каждой строки.
-
как метод расширения. Я нахожу string.Join
раздражающим, потому что он статичен, что означает, что в цепочке операций лексически не в правильном порядке.
/// <summary>
/// Turns all elements in the enumerable to strings and joins them using the
/// specified string as the separator and the specified prefix and suffix for
/// each string.
/// <example>
/// <code>
/// var a = (new[] { "Paris", "London", "Tokyo" }).JoinString(", ", "[", "]");
/// // a contains "[Paris], [London], [Tokyo]"
/// </code>
/// </example>
/// </summary>
public static string JoinString<T>(this IEnumerable<T> values,
string separator = null, string prefix = null, string suffix = null)
{
if (values == null)
throw new ArgumentNullException("values");
using (var enumerator = values.GetEnumerator())
{
if (!enumerator.MoveNext())
return "";
StringBuilder sb = new StringBuilder();
sb.Append(prefix).Append(enumerator.Current.ToString()).Append(suffix);
while (enumerator.MoveNext())
sb.Append(separator).Append(prefix)
.Append(enumerator.Current.ToString()).Append(suffix);
return sb.ToString();
}
}
Ответ 8
AsIEnumerable
/// <summary>
/// Returns a sequence containing one element.
/// </summary>
public static IEnumerable<T> AsIEnumerable<T>(this T obj)
{
yield return obj;
}
Использование
var nums = new[] {12, 20, 6};
var numsWith5Prepended = 5.AsIEnumerable().Concat(nums);
Ответ 9
Заказ
/// <summary>Sorts the elements of a sequence in ascending order.</summary>
public static IEnumerable<T> Order<T>(this IEnumerable<T> source)
{
return source.OrderBy(x => x);
}
Ответ 10
В случайном порядке
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)
{
var random = new Random();
return items.OrderBy(x => random.Next());
}
EDIT: Кажется, есть несколько проблем с вышеупомянутой реализацией. Вот улучшенный вариант на основе кода @LukeH и комментарии от @ck и @Strilanc.
private static Random _rand = new Random();
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
var items = source == null ? new T[] { } : source.ToArray();
var count = items.Length;
while(count > 0)
{
int toReturn = _rand.Next(0, count);
yield return items[toReturn];
items[toReturn] = items[count - 1];
count--;
}
}
Ответ 11
MinElement
Min
возвращает только минимальное значение, возвращаемое указанным выражением, но не исходный элемент, который дал этот минимальный элемент.
/// <summary>Returns the first element from the input sequence for which the
/// value selector returns the smallest value.</summary>
public static T MinElement<T, TValue>(this IEnumerable<T> source,
Func<T, TValue> valueSelector) where TValue : IComparable<TValue>
{
if (source == null)
throw new ArgumentNullException("source");
if (valueSelector == null)
throw new ArgumentNullException("valueSelector");
using (var enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new InvalidOperationException("source contains no elements.");
T minElem = enumerator.Current;
TValue minValue = valueSelector(minElem);
while (enumerator.MoveNext())
{
TValue value = valueSelector(enumerator.Current);
if (value.CompareTo(minValue) < 0)
{
minValue = value;
minElem = enumerator.Current;
}
}
return minElem;
}
}
Ответ 12
Loop
Вот что-то классное, о котором я только что подумал. (Если бы я только подумал об этом, может быть, это не так полезно? Но я подумал об этом, потому что я использую его.) Повторяйте последовательность последовательно, чтобы создать бесконечную последовательность. Это выполняет нечто вроде того, что вам дают Enumerable.Range
и Enumerable.Repeat
, за исключением того, что оно может использоваться для произвольной (в отличие от Range
) последовательности (в отличие от Repeat
):
public static IEnumerable<T> Loop<T>(this IEnumerable<T> source)
{
while (true)
{
foreach (T item in source)
{
yield return item;
}
}
}
Использование:
var numbers = new[] { 1, 2, 3 };
var looped = numbers.Loop();
foreach (int x in looped.Take(10))
{
Console.WriteLine(x);
}
Вывод:
1
2
3
1
2
3
1
2
3
1
Примечание. Я полагаю, вы могли бы выполнить это с помощью чего-то вроде:
var looped = Enumerable.Repeat(numbers, int.MaxValue).SelectMany(seq => seq);
... но я думаю, что Loop
понятнее.
Ответ 13
IndexOf
/// <summary>
/// Returns the index of the first element in this <paramref name="source"/>
/// satisfying the specified <paramref name="condition"/>. If no such elements
/// are found, returns -1.
/// </summary>
public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> condition)
{
if (source == null)
throw new ArgumentNullException("source");
if (condition == null)
throw new ArgumentNullException("condition");
int index = 0;
foreach (var v in source)
{
if (condition(v))
return index;
index++;
}
return -1;
}
Ответ 14
Куски
Возвращает куски определенного размера. x.Chunks(2)
of 1,2,3,4,5
вернет два массива с 1,2
и 3,4
. x.Chunks(2,true)
вернет 1,2
, 3,4
и 5
.
public static IEnumerable<T[]> Chunks<T>(this IEnumerable<T> xs, int size, bool returnRest = false)
{
var curr = new T[size];
int i = 0;
foreach (var x in xs)
{
if (i == size)
{
yield return curr;
i = 0;
curr = new T[size];
}
curr[i++] = x;
}
if (returnRest)
yield return curr.Take(i).ToArray();
}
Ответ 15
ToHashSet
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
return new HashSet<T>(items);
}
Ответ 16
FirstOrDefault со значением по умолчанию
/// <summary>
/// Returns the first element of a sequence, or a default value if the
/// sequence contains no elements.
/// </summary>
/// <typeparam name="T">The type of the elements of
/// <paramref name="source"/>.</typeparam>
/// <param name="source">The <see cref="IEnumerable<T>"/> to return
/// the first element of.</param>
/// <param name="default">The default value to return if the sequence contains
/// no elements.</param>
/// <returns><paramref name="default"/> if <paramref name="source"/> is empty;
/// otherwise, the first element in <paramref name="source"/>.</returns>
public static T FirstOrDefault<T>(this IEnumerable<T> source, T @default)
{
if (source == null)
throw new ArgumentNullException("source");
using (var e = source.GetEnumerator())
{
if (!e.MoveNext())
return @default;
return e.Current;
}
}
/// <summary>
/// Returns the first element of a sequence, or a default value if the sequence
/// contains no elements.
/// </summary>
/// <typeparam name="T">The type of the elements of
/// <paramref name="source"/>.</typeparam>
/// <param name="source">The <see cref="IEnumerable<T>"/> to return
/// the first element of.</param>
/// <param name="predicate">A function to test each element for a
/// condition.</param>
/// <param name="default">The default value to return if the sequence contains
/// no elements.</param>
/// <returns><paramref name="default"/> if <paramref name="source"/> is empty
/// or if no element passes the test specified by <paramref name="predicate"/>;
/// otherwise, the first element in <paramref name="source"/> that passes
/// the test specified by <paramref name="predicate"/>.</returns>
public static T FirstOrDefault<T>(this IEnumerable<T> source,
Func<T, bool> predicate, T @default)
{
if (source == null)
throw new ArgumentNullException("source");
if (predicate == null)
throw new ArgumentNullException("predicate");
using (var e = source.GetEnumerator())
{
while (true)
{
if (!e.MoveNext())
return @default;
if (predicate(e.Current))
return e.Current;
}
}
}
Ответ 17
InsertBetween
Вставляет элемент между каждой парой последовательных элементов.
/// <summary>Inserts the specified item in between each element in the input
/// collection.</summary>
/// <param name="source">The input collection.</param>
/// <param name="extraElement">The element to insert between each consecutive
/// pair of elements in the input collection.</param>
/// <returns>A collection containing the original collection with the extra
/// element inserted. For example, new[] { 1, 2, 3 }.InsertBetween(0) returns
/// { 1, 0, 2, 0, 3 }.</returns>
public static IEnumerable<T> InsertBetween<T>(
this IEnumerable<T> source, T extraElement)
{
return source.SelectMany(val => new[] { extraElement, val }).Skip(1);
}
Ответ 18
EmptyIfNull
Это спорный вопрос; Я уверен, что многие пуристы будут возражать против "метода экземпляра" на null
.
/// <summary>
/// Returns an IEnumerable<T> as is, or an empty IEnumerable<T> if it is null
/// </summary>
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Применение:
foreach(var item in myEnumerable.EmptyIfNull())
{
Console.WriteLine(item);
}
Ответ 19
Анализировать
В этом состоит пользовательский делегат (вместо этого он мог использовать интерфейс IParser<T>
, но я пошел с делегатом, поскольку он был проще), который используется для синтаксического анализа последовательности строк в последовательности значений, пропуская элементы, в которых синтаксический анализ не выполняется.
public delegate bool TryParser<T>(string text, out T value);
public static IEnumerable<T> Parse<T>(this IEnumerable<string> source,
TryParser<T> parser)
{
source.ThrowIfNull("source");
parser.ThrowIfNull("parser");
foreach (string str in source)
{
T value;
if (parser(str, out value))
{
yield return value;
}
}
}
Использование:
var strings = new[] { "1", "2", "H3llo", "4", "five", "6", "se7en" };
var numbers = strings.Parse<int>(int.TryParse);
foreach (int x in numbers)
{
Console.WriteLine(x);
}
Вывод:
1
2
4
6
Именование сложного для этого. Я не уверен, что Parse
- лучший вариант (это просто, по крайней мере), или если что-то вроде ParseWhereValid
будет лучше.
Ответ 20
AssertCount
Эффективно определяет, содержит ли a IEnumerable<T>
не менее/точно/не более определенного количества элементов.
public enum CountAssertion
{
AtLeast,
Exact,
AtMost
}
/// <summary>
/// Asserts that the number of items in a sequence matching a specified predicate satisfies a specified CountAssertion.
/// </summary>
public static bool AssertCount<T>(this IEnumerable<T> source, int countToAssert, CountAssertion assertion, Func<T, bool> predicate)
{
if (source == null)
throw new ArgumentNullException("source");
if (predicate == null)
throw new ArgumentNullException("predicate");
return source.Where(predicate).AssertCount(countToAssert, assertion);
}
/// <summary>
/// Asserts that the number of elements in a sequence satisfies a specified CountAssertion.
/// </summary>
public static bool AssertCount<T>(this IEnumerable<T> source, int countToAssert, CountAssertion assertion)
{
if (source == null)
throw new ArgumentNullException("source");
if (countToAssert < 0)
throw new ArgumentOutOfRangeException("countToAssert");
switch (assertion)
{
case CountAssertion.AtLeast:
return AssertCountAtLeast(source, GetFastCount(source), countToAssert);
case CountAssertion.Exact:
return AssertCountExact(source, GetFastCount(source), countToAssert);
case CountAssertion.AtMost:
return AssertCountAtMost(source, GetFastCount(source), countToAssert);
default:
throw new ArgumentException("Unknown CountAssertion.", "assertion");
}
}
private static int? GetFastCount<T>(IEnumerable<T> source)
{
var genericCollection = source as ICollection<T>;
if (genericCollection != null)
return genericCollection.Count;
var collection = source as ICollection;
if (collection != null)
return collection.Count;
return null;
}
private static bool AssertCountAtMost<T>(IEnumerable<T> source, int? fastCount, int countToAssert)
{
if (fastCount.HasValue)
return fastCount.Value <= countToAssert;
int countSoFar = 0;
foreach (var item in source)
{
if (++countSoFar > countToAssert) return false;
}
return true;
}
private static bool AssertCountExact<T>(IEnumerable<T> source, int? fastCount, int countToAssert)
{
if (fastCount.HasValue)
return fastCount.Value == countToAssert;
int countSoFar = 0;
foreach (var item in source)
{
if (++countSoFar > countToAssert) return false;
}
return countSoFar == countToAssert;
}
private static bool AssertCountAtLeast<T>(IEnumerable<T> source, int? fastCount, int countToAssert)
{
if (countToAssert == 0)
return true;
if (fastCount.HasValue)
return fastCount.Value >= countToAssert;
int countSoFar = 0;
foreach (var item in source)
{
if (++countSoFar >= countToAssert) return true;
}
return false;
}
Использование
var nums = new[] { 45, -4, 35, -12, 46, -98, 11 };
bool hasAtLeast3Positive = nums.AssertCount(3, CountAssertion.AtLeast, i => i > 0); //true
bool hasAtMost1Negative = nums.AssertCount(1, CountAssertion.AtMost, i => i < 0); //false
bool hasExactly2Negative = nums.AssertCount(2, CountAssertion.Exact, i => i < 0); //false
Ответ 21
ZipMerge
Это моя версия Zip
, которая работает как настоящая молния. Он не проецирует два значения в один, а возвращает объединенный IEnumerable. Возможны перегрузки, пропуская правый и/или левый хвост.
public static IEnumerable<TSource> ZipMerge<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second)
{
using (var secondEnumerator = second.GetEnumerator())
{
foreach (var item in first)
{
yield return item;
if (secondEnumerator.MoveNext())
yield return secondEnumerator.Current;
}
while (secondEnumerator.MoveNext())
yield return secondEnumerator.Current;
}
}
Ответ 22
RandomSample
Здесь простая функция, полезная, если у вас есть большой набор данных (скажем, более 100 элементов), и вы хотите просто наблюдать за ним случайную выборку.
public static IEnumerable<T> RandomSample<T>(this IEnumerable<T> source,
double percentage)
{
source.ThrowIfNull("source");
var r = new Random();
return source.Where(x => (r.NextDouble() * 100.0) < percentage);
}
Использование:
List<DataPoint> data = GetData();
// Sample roughly 3% of the data
var sample = data.RandomSample(3.0);
// Verify results were correct for this sample
foreach (DataPoint point in sample)
{
Console.WriteLine("{0} => {1}", point, DoCalculation(point));
}
Примечания:
- Не подходит для крошечных коллекций, поскольку количество возвращаемых элементов является вероятностным (может легко вернуть нуль на маленькой последовательности).
- Не подходит для огромных коллекций или запросов к базе данных, поскольку он включает перечисление по каждому элементу в последовательности.
Ответ 23
One, Two, MoreThanOne, AtLeast, AnyAtAll
public static bool One<T>(this IEnumerable<T> enumerable)
{
using (var enumerator = enumerable.GetEnumerator())
return enumerator.MoveNext() && !enumerator.MoveNext();
}
public static bool Two<T>(this IEnumerable<T> enumerable)
{
using (var enumerator = enumerable.GetEnumerator())
return enumerator.MoveNext() && enumerator.MoveNext() && !enumerator.MoveNext();
}
public static bool MoreThanOne<T>(this IEnumerable<T> enumerable)
{
return enumerable.Skip(1).Any();
}
public static bool AtLeast<T>(this IEnumerable<T> enumerable, int count)
{
using (var enumerator = enumerable.GetEnumerator())
for (var i = 0; i < count; i++)
if (!enumerator.MoveNext())
return false;
return true;
}
public static bool AnyAtAll<T>(this IEnumerable<T> enumerable)
{
return enumerable != null && enumerable.Any();
}
Ответ 24
Окно
Перечисляет массивы ( "окна" ) с длиной size
, содержащей самые последние значения.
{ 0, 1, 2, 3 }
переходит в { [0, 1], [1, 2], [2, 3] }
.
Я использую это, например, для рисования линейного графика путем соединения двух точек.
public static IEnumerable<TSource[]> Window<TSource>(
this IEnumerable<TSource> source)
{
return source.Window(2);
}
public static IEnumerable<TSource[]> Window<TSource>(
this IEnumerable<TSource> source, int size)
{
if (size <= 0)
throw new ArgumentOutOfRangeException("size");
return source.Skip(size).WindowHelper(size, source.Take(size));
}
private static IEnumerable<TSource[]> WindowHelper<TSource>(
this IEnumerable<TSource> source, int size, IEnumerable<TSource> init)
{
Queue<TSource> q = new Queue<TSource>(init);
yield return q.ToArray();
foreach (var value in source)
{
q.Dequeue();
q.Enqueue(value);
yield return q.ToArray();
}
}
Ответ 25
SkipLast и TakeLast
/// <summary>
/// Enumerates the items of this collection, skipping the last
/// <paramref name="count"/> items. Note that the memory usage of this method
/// is proportional to <paramref name="count"/>, but the source collection is
/// only enumerated once, and in a lazy fashion. Also, enumerating the first
/// item will take longer than enumerating subsequent items.
/// </summary>
public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (count < 0)
throw new ArgumentOutOfRangeException("count",
"count cannot be negative.");
if (count == 0)
return source;
return skipLastIterator(source, count);
}
private static IEnumerable<T> skipLastIterator<T>(IEnumerable<T> source,
int count)
{
var queue = new T[count];
int headtail = 0; // tail while we're still collecting, both head & tail
// afterwards because the queue becomes completely full
int collected = 0;
foreach (var item in source)
{
if (collected < count)
{
queue[headtail] = item;
headtail++;
collected++;
}
else
{
if (headtail == count) headtail = 0;
yield return queue[headtail];
queue[headtail] = item;
headtail++;
}
}
}
/// <summary>
/// Returns a collection containing only the last <paramref name="count"/>
/// items of the input collection. This method enumerates the entire
/// collection to the end once before returning. Note also that the memory
/// usage of this method is proportional to <paramref name="count"/>.
/// </summary>
public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (count < 0)
throw new ArgumentOutOfRangeException("count",
"count cannot be negative.");
if (count == 0)
return new T[0];
var queue = new Queue<T>(count + 1);
foreach (var item in source)
{
if (queue.Count == count)
queue.Dequeue();
queue.Enqueue(item);
}
return queue.AsEnumerable();
}
Ответ 26
WhereIf
Дополнительное предложение Where
на IEnumerable
и IQueryable
. Избегает выполнения инструкций при построении предикатов и лямбда для запроса. Полезно, если во время компиляции вы не знаете, должен ли фильтр применяться.
public static IEnumerable<TSource> WhereIf<TSource>(
this IEnumerable<TSource> source, bool condition,
Func<TSource, bool> predicate)
{
return condition ? source.Where(predicate) : source;
}
Useage:
var custs = Customers.WhereIf(someBool, x=>x.EyeColor=="Green");
LINQ WhereIf На ExtensionMethod.NET и заимствован из Andrew blog.
Ответ 27
Дубликаты
Используется в сочетании с методом Ani AssertCount
(я использую один из них под названием CountAtLeast
), становится очень легко найти элементы в последовательности, которая появляются несколько раз:
public static IEnumerable<T> Duplicates<T, TKey>(this IEnumerable<T> source,
Func<T, TKey> keySelector = null, IEqualityComparer<TKey> comparer = null)
{
source.ThrowIfNull("source");
keySelector = keySelector ?? new Func<T, TKey>(x => x);
comparer = comparer ?? EqualityComparer<TKey>.Default;
return source.GroupBy(keySelector, comparer)
.Where(g => g.CountAtLeast(2))
.SelectMany(g => g);
}
Ответ 28
ToList и ToDictionary с начальной загрузкой
Перегрузки ToList и ToDictionary, которые выставляют исходную емкость базовых классов. Иногда полезно, когда длина источника известна или ограничена.
public static List<TSource> ToList<TSource>(
this IEnumerable<TSource> source,
int capacity)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var list = new List<TSource>(capacity);
list.AddRange(source);
return list;
}
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
int capacity,
IEqualityComparer<TKey> comparer = null)
{
return source.ToDictionary<TSource, TKey, TSource>(
keySelector, x => x, capacity, comparer);
}
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
int capacity,
IEqualityComparer<TKey> comparer = null)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (keySelector == null)
{
throw new ArgumentNullException("keySelector");
}
if (elementSelector == null)
{
throw new ArgumentNullException("elementSelector");
}
var dictionary = new Dictionary<TKey, TElement>(capacity, comparer);
foreach (TSource local in source)
{
dictionary.Add(keySelector(local), elementSelector(local));
}
return dictionary;
}
Ответ 29
CountUpTo
static int CountUpTo<T>(this IEnumerable<T> source, int maxCount)
{
if (maxCount == 0)
return 0;
var genericCollection = source as ICollection<T>;
if (genericCollection != null)
return Math.Min(maxCount, genericCollection.Count);
var collection = source as ICollection;
if (collection != null)
return Math.Min(maxCount, collection.Count);
int count = 0;
foreach (T item in source)
if (++count >= maxCount)
break;
return count;
}
Ответ 30
Coalesce
public static T Coalesce<T>(this IEnumerable<T> items) {
return items.Where(x => x != null && !x.Equals(default(T))).FirstOrDefault();
// return items.OfType<T>().FirstOrDefault(); // Gabe take
}