0

I have two separate lists as:

  • List<string> keys = new List<string>() { "A", "A", "B","B","C","C" };
  • List<datetime> dates = new List<datetime>() { 1/1/2000 12:00AM, 1/1/2000 12:30AM, 1/2/2000 12:00AM, 1/2/2000 12:30AM, 5/1/2000 12:00AM, 5/1/2000 12:30AM };

I would like to build a dict<string,List<datetime>>. Expected output is:

  • Dict[0] = A, (1/1/2000 12:00AM, 1/1/2000 12:30AM)

  • Dict[1] = B,(1/2/2000 12:00AM, 1/2/2000 12:30AM)

  • Dict[2] = C, (5/1/2000 12:00AM, 5/1/2000 12:30AM )

How can I achieve this?

This is how I was approaching it but to no avail:

for (int i = 0; i < keys.Count; i++)
            {
                var id = keys.ElementAt(i);
                for (int j = 0; j < dates.Count; j++)
                {
                    List<DateTime> values;
                    if (!dict.TryGetValue(id, out values))
                    {
                        values = new List<DateTime>();
                        dict[id] = values;
                    }
                    values.Add(dates.GetSampleTimeAt(j));
                }
            }
user7157732
  • 347
  • 1
  • 8
  • 24
  • duplicate of http://stackoverflow.com/questions/4038978/map-two-lists-into-a-dictionary-in-c-sharp ? – Peter Ritchie Jan 25 '17 at 16:54
  • @PeterRitchie: I saw that post but over there, keys were already unique..here List elements are not unique.. – user7157732 Jan 25 '17 at 16:55
  • why was this downvoted? :( – user7157732 Jan 25 '17 at 17:00
  • 1
    I presume it was downvoted because you hadn't initially shown what you tried. As it is your approach is not bad except that you only want one loop since when you are looking at the key at `i` you also want the date at `i`. – Chris Jan 25 '17 at 17:01

1 Answers1

8

It's very simple with LINQ:

keys.Zip(dates, (key,date) => new { key, date })
    .GroupBy(x => x.key)
    .ToDictionary(g => g.Key, g => g.Select(x => x.date).ToList())

Explanations:

  1. Zip corresponding items from two sequences into anonymous object
  2. Group anonymous objects by value of key
  3. Convert groups to dictionary
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459