public class InvestorMailing
{
    public string To { get; set; }

    public IEnumerable<string> Attachments { get; set; }

    public int AttachmentCount { get; set; }

    public long AttachmentSize { get; set; }
}


我有一个IList<InvestorMailing> mailingList。如果附件大小大于x,则需要将对象拆分为多个块。有没有简单的linq-y方法来做到这一点?

编辑:

这就是我生成邮件的方式:

        var groupedMailings = mailingList.GroupBy(g => g.GroupBy);

        var investorMailings = groupedMailings.Select(
            g => new DistinctInvestorMailing
            {
                Id = g.Select(x => x.Id).FirstOrDefault(),
                To = g.Key.Trim(),
                From = g.Select(x => x.From).FirstOrDefault(),
                FromName = g.Select(x => x.FromName).FirstOrDefault(),
                Bcc = g.Select(x => x.Bcc).FirstOrDefault(),
                DeliveryCode = g.Select(x => x.DeliveryCode).FirstOrDefault(),
                Subject = g.Select(x => x.Subject).FirstOrDefault(),
                Body = g.Select(x => x.Body).FirstOrDefault(),
                CommentsOnStatus = g.Select(x => x.CommentsOnStatus).FirstOrDefault(),
                Attachments = g.Select(x => x.AttachmentPath),
                AttachmentCount = g.Select(x => x.AttachmentPath).Count(),
                AttachmentSize = g.Sum(x => x.AttachmentSize),
                MailType = g.Select(x => x.MessageType).FirstOrDefault()
            }
        ).ToList();

最佳答案

使用标准方法进行操作应该非常简单。考虑以下示例:

class Foo
{
    public Foo(int weight) { Weight = weight; }
    public int Weight { get; set; }
}


...

IEnumerable<IList<Foo>> GroupFoosByWeight(IList<Foo> foos, int weightLimit)
{
    List<Foo> list = new List<Foo>();
    int sumOfWeight = 0;

    foreach (Foo foo in foos)
    {
        if (sumOfWeight + foo.Weight > weightLimit)
        {
            yield return list;
            sumOfWeight = 0;
            list.Clear();
        }

        list.Add(foo);
        sumOfWeight += foo.Weight;
    }

    if (list.Count > 0)
        yield return list;
}


...

List<Foo> foos = new List<Foo>()
{
    new Foo(15), new Foo(32), new Foo(14), new Foo(19), new Foo(27)
};

foreach (IList<Foo> list in GroupFoosByWeight(foos, 35))
{
    Console.WriteLine("{0}\t{1}", list.Count, list.Sum(f => f.Weight));
}


编辑

我做了一些工作,并制作了LINQ版本。在这种情况下,它实际上并没有节省太多代码,但这只是一个开始。

int weightLimit = 35;
int fooGroup = 0;
int totalWeight = 0;

Func<Foo, int> groupIncrementer = f =>
{
    if (totalWeight + f.Weight > weightLimit)
    {
        fooGroup++;
        totalWeight = 0;
    }

    totalWeight += f.Weight;

    return fooGroup;
};

var query = from foo in foos
            group foo by new { Group = groupIncrementer(foo) }
                into g
                select g.AsEnumerable();

foreach (IList<Foo> list in query)
{
    Console.WriteLine("{0}\t{1}", list.Count, list.Sum(f => f.Weight));
}

关于c# - 如何基于某些属性将对象分成多个块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2693016/

10-08 22:25