列表作为值列表 [英] Dictionary with list as value

查看:54
本文介绍了列表作为值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello All,

我是编程新手,我需要你帮助创建这个逻辑。



我有两个班级路线和停止



每条路线都有很多站点。每个站点都有它自己的属性。

我创建了一个字典,其中包含作为键的路径和停靠列表作为值。

没有问题。



现在我遇到的问题是我已经创建了一个类型为stop的列表,我正在为该路由添加stop到该列表,然后该列表将作为值添加到字典中和路线将是关键。问题是在下次第一次路由迭代之后,我将再次必须将停止细节添加到已有数据的列表中。因此记录将被追加并且整个过程变得浪费,因为实际上我必须将新列表添加到字典作为值。



我将如何创建新的每次迭代的列表。我不认为每次创建一个新列表都是个好主意。请建议我该怎么办。





Hello All ,
I am new to programming and i need you help to create this logic.

I have two classes Routes and Stops

there can be many stops at each route. Also each stop has it's own properties.
I have created a dictionary that has route as key and list of stops as value.
No problems there.

Now where i am getting stuck is that i have created a list of type stop and i am adding stop to that list for a route and this list will then be added to the dictionary as value and route will be the key. Problem is after first iteration of routes next time i will again have to add stop detail to the list which already has data. so records will be appended and whole process goes to waste where as in fact i have to add a new list to the dictionary as value.

how will i create a new list for every iteration. and i don't think creating a new list every time is a good idea. Please suggest what should i do.


 public Dictionary<string, List<Stops>> MyRoute = new Dictionary<string, List< Stops>>();
        public List<Stops> RouteStops = new List< Stops>();


class Stops
    {
        public String Id { get; set; }
        public string name { get; set; }
        public int sequence { get; set; }
        public string Key { get; set; }
    }

推荐答案

类似于:

Something like:
public Dictionary<string, List<Stops>> MyRoute = new Dictionary<string, List< Stops>>();
public List<Stops> RouteStops = new List< Stops>();
public void MyMethod(int n)
   {
   int j = 0;
   for (int i = 0; i < n; i++)
      {
      RouteStops = new List<Stops>();
      Stop stop = new Stop();
      stop.Id = string.Format("{0}:{1}", i, j++);
      RouteStops.Add(stop);
      stop = new Stop();
      stop.Id = string.Format("{0}:{1}", i, j++);
      RouteStops.Add(stop);
      MyRoute.Add(i.ToString(), RouteStops);
      }
   }


这篇关于列表作为值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆