使用GroupBy对列表元素进行分组

本文关键字:列表元素 GroupBy 使用 | 更新日期: 2023-09-27 18:25:15

对于我想进行的一些分组,我在使用LINQ表达式时遇到了一些麻烦。我有一个大概几千封必须发送的邮件的大列表,我想把它们分成2000封邮件的列表,并把它们放在一个父列表中。原始列表如下:List<Recipient>()

收件人有姓名、地址等

我已经写了我想用foreach做什么,但如果可能的话,我想把它作为LINQ表达式,我似乎无法理解。

private List<List<Recipient>> PhysicalPageList(List<Recipient> recipients)
    {
        var pageList = new List<List<Recipient>>();
        var smallList = new List<Recipient>();
        foreach (var rec in recipients) 
        {
            smallList.Add(rec);
            if (smallList.Count % 2000 == 0) { continue; }
            var tmpList = new List<Recipient>();
            tmpList.AddRange(smallList);
            pageList.Add(smallList);
            smallList.Clear();
        }
        if (smallList.Count() != 0)
        {
            var tmpList = new List<Recipient>();
            tmpList.AddRange(smallList);
            pageList.Add(tmpList);
            smallList.Clear();
        }
        return pageList;
    }

我有一个关于字符串而不是接收者的例子(我自己还没有写过):

    private List<List<string>> PageList(List<string> recipients)
    {
        return recipients.Select((x, i) => new { Index = i, Value = x })
                                        .GroupBy(x => x.Index / 2000) 
                                        .Select(x => x.Select(v => v.Value).ToList())
                                        .ToList();
    }

我也尝试过,但LINQ不允许我从收件人列表中进行选择。

使用GroupBy对列表元素进行分组

为什么不试试这个?

private List<List<Recipient>> PageList(List<Recipient> recipients)
{
    return recipients.Select((x, i) => new { Index = i, Value = x })
                     .GroupBy(x => x.Index / 2000) 
                     .Select(x => x.Select(v => v.Value).ToList())
                     .ToList();
}