我有两个单独的列表:
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));
}
}
答案 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())
说明: