开发者

Creating Generic Collection within a collection

I have two classes and want to build a collection that contains a collection. Thus I have..

public class GenericReportInfo 
{
    public string ReportName { get开发者_StackOverflow社区; set; }
    public string ReportFileName { get; set; }
    public Paramaters parameterList { get; set; }
}

public class Paramaters 
{
    public List<string> parameter { get; set; }

}

And want to get to the point where I can simply add to the collection inline ie

public class GenericReportsInfo
{
   public List<GenericReportInfo> CreateAndInitialize()
   {
       List<GenericReportInfo> reportsList = new List<GenericReportInfo>();
       GenericReportInfo info = new GenericReportInfo() 
         { "Agent", "Agent", new paramter() {"StateId"} };

       return reportsList;
   }
}

Just would like know the correct way to get to this.

Regards

Mark


You're almost there:

List<GenericReportInfo> reportsList = new List<GenericReportInfo>();
GenericReportInfo info = new GenericReportInfo()
{
    ReportName = "Agent",
    ReportFileName = "Agent",
    parameterList = new Paramaters() { parameter = new List<string> { "StateId" } }
};

I'd like to add a few comments, though:

  • It should be Parameters, not Paramaters.
  • I would capitalize ParameterList as well (like the other public properties).
  • Unless you expect the Parameters class to contain more fields in the future, I'm not sure if it's worth to have an extra class for this (just to encapsulate a List<String>).


Heinzi's answer is correct. But just for completeness, you could also create a constructor that takes the standard fields as well as a param array of your Parameter type. If your class is small it can be a cleaner syntax.


Instead of having a list of strings you could have a list of parameters instead...

public class GenericReportInfo 
{
    public string ReportName { get; set; }
    public string ReportFileName { get; set; }
    public IList<Parameter> Parameters { get; set; }

    public GenericReportInfo(
        string reportName,
        string reportFileName,
        IEnumerable<Parameter> parameters)
    {
        ReportName = reportName;
        ReportFileName = reportFileName;
        Parameters = new List<Parameter>(parameters);
    }
}

public class Parameter 
{
    public string Name { get; set; }
}

Then to initialise...

GenericReportInfo info = new GenericReportInfo()
{
    ReportName = "Agent",
    ReportFileName = "Agent",
    Parameters = new List<Parameter>() { new Parameter(){ Name = "StateId" } }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜