LINQ 分区列表成 8 个成员的列表 [英] LINQ Partition List into Lists of 8 members

查看:17
本文介绍了LINQ 分区列表成 8 个成员的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一个列表(使用 LINQ)分解成一个列表列表,在每 8 个条目上对原始列表进行分区?

How would one take a List (using LINQ) and break it into a List of Lists partitioning the original list on every 8th entry?

我想这样的事情会涉及到 Skip 和/或 Take,但我对 LINQ 还是很陌生.

I imagine something like this would involve Skip and/or Take, but I'm still pretty new to LINQ.

使用 C#/.Net 3.5

Using C# / .Net 3.5

Edit2:这个问题的措辞与其他重复"问题不同.虽然问题相似,但这个问题的答案更胜一筹:接受"的答案都非常可靠(使用 yield 声明)以及 Jon Skeet 建议使用 MoreLinq(不推荐)在其他"问题中.)有时重复是好的,因为它们迫使重新检查问题.

This question is phrased differently than the other "duplicate" question. Although the problems are similar, the answers in this question are superior: Both the "accepted" answer is very solid (with the yield statement) as well as Jon Skeet's suggestion to use MoreLinq (which is not recommended in the "other" question.) Sometimes duplicates are good in that they force a re-examination of a problem.

推荐答案

使用下面的扩展方法将输入分成子集

Use the following extension method to break the input into subsets

public static class IEnumerableExtensions
{
    public static IEnumerable<List<T>> InSetsOf<T>(this IEnumerable<T> source, int max)
    {
        List<T> toReturn = new List<T>(max);
        foreach(var item in source)
        {
                toReturn.Add(item);
                if (toReturn.Count == max)
                {
                        yield return toReturn;
                        toReturn = new List<T>(max);
                }
        }
        if (toReturn.Any())
        {
                yield return toReturn;
        }
    }
}

这篇关于LINQ 分区列表成 8 个成员的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆