首页 > 解决方案 > 如何在 C# 中填充对象的嵌套列表

问题描述

我有一个类,如下所示:

public class Par
    {
        public string id { get { return id; } set { id = value; } }
        public Int32 num { get { return num; } set { num = value; } }
}

现在我创建了一个名为“Msg”的类,它有一个嵌套的 Par 对象列表

public class Msg 
    {
        private Int32 mid; 
        private Int32 mnum; 
        public List<Par> pList; //list of Par objects

        //constructor of Msg
        public Msg(Int32 mid, Int32 mnum)
        {
            this.mid = mid;
            this.mnum = mnum;
            this.pList = new List<Par>();
        }
  
public void add_ParObject_To_pList(Par obj) 
        {
            pList.Add(obj);
        }

在 main 方法中,我遍历文本文件的每一行并使用 foreach 循环提取其内容

foreach (string line in lines)
//I have instantiated a list of Msg objects named "MList"
    List<Msg> MList = new List<Msg>();

    //my code to extract data from each line 

    Par pobj = new Par(id, num); //instantiating a Par object 

    //code to check within MList if there exists a Msg object with extracted mid and mnum values from file. If not, then new Msg object must be added to this list passing in this mid and mnum.
    MList.Add(new Msg(mid, mnum));







 


    

问题:我如何调用和填充嵌套的“pList”(包含 id 和 num 的 Par 对象的列表),它属于这个 foreach 循环中的 Msg 对象?

此外,这是我的文本文件中的示例数据:

ID
1 10 1000 200
1 10 2000 201
2 20 1000 101
2 20 2000 102

目标是代码应将 MList(Msg 对象列表)中的数据排列如下(基于提供的示例数据):

msglist[0] -> 1, 10 pList[0]: 1000 200, pList[1]: 2000 201

msglist[1] -> 2, 20 pList[0]: 1000 101, pList[1]: 2000 102

我将不胜感激任何建议/意见。提前致谢。

标签: c#nestedinitializationnested-listsobject-oriented-analysis

解决方案


在解析文件时保留 Msg 字典,而不是 List;字典的查找速度很快,您将对每一行进行查找

var msgs = new Dictionary<string, Msg>();

foreach(var line in File.ReadAllLines("path to file"){

  //code to get the column values from line here blah blah
  var mid = ...
  var mnum = ...

  //msg caching logic 

  if(!msgs.ContainsKey(mid))
    msgs[mid] = new Msg(mid, mnum);

  var p = new Par(...)

  msgs[mid].pList.Add(p);

}

您可以保留字典并使用它,或者如果您想要列表/数组/可枚举等中的所有消息,您可以访问字典的.Values属性

请命名pList->PListadd_ParObject_To_pList-> AddParObjectToPList(或丢弃该方法;该列表是公开的)。在 c# PublicPropertiesAndMethodsArePascalCase


推荐阅读