如何从两个单独的列表创建dict - C#

时间:2017-01-25 16:52:17

标签: c# dictionary

我有两个单独的列表:

  • 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 };

我想构建一个dict<string,List<datetime>>。预期产出是:

  • 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 )

我怎样才能做到这一点?

这就是我接近它的方式,但无济于事:

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));
                }
            }

1 个答案:

答案 0 :(得分:7)

使用LINQ非常简单:

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

说明:

  1. Zip两个序列中的相应项目到匿名对象
  2. 按键值
  3. 对匿名对象进行分组
  4. 将群组转换为词典