1

I am looking to created batches from a Dictionary<string, DateTime> with the following constraints:

  1. All items in the batch much share the same date
  2. There can be no more than X items in a single batch. If there are more items with the same date, another batch must be created.

I have worked out the following logic, but was wondering if there was some other more succinct way of doing this with just linq.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dictionary_sort_by_value_test
{
    class Program
    {
        static void Main(string[] args)
        {
            int maxBatchSize = 3;

            Dictionary<string, DateTime> secs = new Dictionary<string, DateTime>();
            secs.Add("6571 JT", new DateTime(2011, 1, 10));
            secs.Add("6572 JT", new DateTime(2011, 1, 12));
            secs.Add("6573 JT", new DateTime(2011, 1, 12));
            secs.Add("6574 JT", new DateTime(2011, 1, 12));
            secs.Add("6575 JT", new DateTime(2011, 1, 10));
            secs.Add("6576 JT", new DateTime(2011, 1, 11));
            secs.Add("6577 JT", new DateTime(2011, 1, 11));
            secs.Add("6578 JT", new DateTime(2011, 1, 11));
            secs.Add("6579 JT", new DateTime(2011, 1, 11));

            var sorted = secs.OrderBy(o => o.Value).GroupBy(o => o.Value);

            foreach (var date in sorted)
            {    
                Console.Write("\nNew batch at {0} \n", date.Key);
                int batchsize = 0;
                foreach (var sec in date)
                {
                    if (batchsize < maxBatchSize)
                    {
                        Console.Write("  {0} {1} \n", sec.Key, sec.Value);
                        batchsize++;
                    }
                    else
                    {
                        Console.Write("\nNew batch at {0} \n", date.Key);
                        Console.Write("  {0} {1} \n", sec.Key, sec.Value);
                        batchsize = 1;
                    }
                }
            }
        }
    }
}
1
  • I don't see where/how you're creating a new batch in your code either. You're counting the number of batches but not every creating a new batch and adding it to your "result". Personally I the only way you could do this using only LINQ would be to have another tie-breaker so you can group by that as well. Or implement your logic as an Extension method on IEnumerable<T>. That way, it's look like LINQ, feel like LINQ and it will be LINQ since that's how LINQ is implemented anyway.
    – Shiv Kumar
    Feb 23, 2011 at 11:11

3 Answers 3

2

You group by your key, then inside the result you group by the item index divided by the desired chunk size.

var chunkSize = 3;
var sorted = secs
    .OrderBy(kv => kv.Key)
    .GroupBy(o => o.Value)
    .Select(g => new {Chunks = g.Select((o,i) => new {Val = o, Index = i})
                                .GroupBy(item => item.Index / chunkSize)});

And displaying it:

 foreach(var item in sorted.SelectMany(item => item.Chunks))
 {
     Console.WriteLine("New batch at " + item.First().Val.Value);
     foreach(var element in item)
         Console.WriteLine(element.Val.Key);
}
2
  • Thanks. This is precisely what I was looking for.
    – Andre P.
    Feb 24, 2011 at 1:26
  • Not exactly nice to look at but I like it and it works.
    – Yes Barry
    Jan 17, 2020 at 17:57
0

Not strictly using linq to solve your problems but a more succinct way of handling the iteration:

static void Main(string[] args)
{
    int maxBatchSize = 3;

    Dictionary<string, DateTime> secs = new Dictionary<string, DateTime>();
    secs.Add("6571 JT", new DateTime(2011, 1, 10));
    secs.Add("6572 JT", new DateTime(2011, 1, 12));
    secs.Add("6573 JT", new DateTime(2011, 1, 12));
    secs.Add("6574 JT", new DateTime(2011, 1, 12));
    secs.Add("6575 JT", new DateTime(2011, 1, 10));
    secs.Add("6576 JT", new DateTime(2011, 1, 11));
    secs.Add("6577 JT", new DateTime(2011, 1, 11));
    secs.Add("6578 JT", new DateTime(2011, 1, 11));
    secs.Add("6574 JT", new DateTime(2011, 1, 11));
    secs.Add("6579 JT", new DateTime(2011, 1, 11));
    secs.Add("6580 JT", new DateTime(2011, 1, 11));
    secs.Add("6581 JT", new DateTime(2011, 1, 11));
    secs.Add("6582 JT", new DateTime(2011, 1, 11));
    secs.Add("6583 JT", new DateTime(2011, 1, 11));

    secs.OrderBy(o => o.Value).GroupBy(o => o.Value).ToList().ForEach(date =>
                   {
                       Console.Write("\nNew batch at {0} \n", date.Key);
                       int batchsize = 0;
                       foreach (var sec in date)
                       {
                           if (batchsize >= maxBatchSize)
                           {
                               Console.Write("\nNew batch at {0} \n", date.Key);
                               batchsize = 0;
                           }

                           Console.Write("  {0} {1} \n", sec.Key, sec.Value);
                           batchsize++;
                       }
                   });

    Console.ReadLine();
}
0

You can do it with 2 GroupBys. First you group by DateTime, and then group by page. I had to specify the generic arguments explicitly, because the compiler was picking the wrong overload, and that made the query code longer.

var groups = secs.GroupBy<KeyValuePair<string, DateTime>, DateTime, string, Group>(
    p => p.Value,
    p => p.Key,
    (d, g) => new Group {
        Date = d,
        Pages = g.Select((s, i) => new KeyValuePair<string, int>(s, i / maxBatchSize))
            .GroupBy<KeyValuePair<string, int>, int, string, Page>(
                p => p.Value,
                p => p.Key,
                (p, g2) => new Page { Id = p, Items = g2.ToList() }) });

foreach (var group in groups)
{
    Console.WriteLine("Date: {0}", group.Date);
    foreach (var page in group.Pages)
    {
        Console.WriteLine("Page: {0}", page.Id);
        foreach (var key in page.Items)
            Console.WriteLine(key);
    }
}

As you can see, I had to define 2 classes because as I said, I had to specify the generic arguments, because using anonymous types made the overload resolution pick another overload.

class Group
{
    public DateTime Date;
    public IEnumerable<Page> Pages;
}

class Page
{
    public int Id;
    public IEnumerable<string> Items;
}

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.