Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Sep 11, 2015

Wrap an object into an IEnumerable of single item

Code:
public static IEnumerable<T> Yield<T>(this T item)
{
    yield return item;
}

Faster TakeBy

Code:
public static IEnumerable<IEnumerable<T>> TakeBy<T>(this IEnumerable<T> source, int count)
{
    var grps = source.Select((val, i) => new { idx = i / count, val }).GroupBy(e => e.idx);
    return grps.Select(g => g.Select(e => e.val));
}

Sep 10, 2015

Combinatorics: get all combinations of k elements from an input sequence


Code:
public static IEnumerable<IEnumerable<T>> Combine<T>(this IEnumerable<T> list, int k = 2, bool repetition = false)
{
    for (int i = 0; i < list.Count(); i++)
    {
        T cur = list.Skip(i).First();
        if (k == 1)
        {
            yield return cur.Yield();
        }
        else
        {
            foreach (var res in list.Skip(i + (repetition ? 0 : 1)).Combine(k - 1, repetition))
            {
                yield return res.Prepend(cur);
            }
        }
    }
}

e.g.
{ 1, 2, 3 }.Combine(2) = {{ 1, 2 }, { 1, 3 }, { 2, 3 }}
{ 1, 2 }.Combine(2, true) = {{ 1, 1 }, { 1, 2 }, { 2, 2 }}
{ 1, 2, 3, 4 }.Combine(3) = {{ 1, 2, 3 }, { 1, 2, 4 }, { 2, 3, 4 }}

May 19, 2015

Linq TakeBy

I was about to write such an extension
But then desided to google for it first, and voila:

Code:
/// <summary>
/// <paramref name="source"/>中の要素を<paramref name="count"/>
/// 個ごとにまとめ直します。
/// 最後の要素数が足りない場合は足りないまま返します。
/// </summary>
public static IEnumerable<IEnumerable<TSource>> TakeBy<TSource>(this IEnumerable<TSource> source, int count)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (count < 1)
    {
        throw new ArgumentOutOfRangeException("count");
    }
    while (source.Any())
    {
        yield return source.Take(count);
        source = source.Skip(count);
    }
}

got it here
Isn't it nice?

ps: this variant is much faster