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

查看:95
本文介绍了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?

我想像这样的事情会涉及跳过"和/或取走",但是我对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天全站免登陆