开发者

C# - Entity to help with row creation

Given class:

   class SomeClass
    {
    public int intdata {get;set;}
    public string stringdata {get;set;}
    public double doubledata {get;set;}
    public string[] ToStringArray开发者_运维百科()
    {
       string one = intdata.ToString();
       string two = stringdata;
       string three = String.Format("{0:C}", doubledata);
       return new string[] {one,two,three};
    }
    }

Let's say we have 5 instances of SomeClass. I want to take these instances and insert organize them into rows.

class RowHelper
{
   public void List<string[]> Rows;

   public RowHelper()
   {
      Rows = new List<string[]>();
   }
   public void CreateRows(SomeClass[] SomeClasses)
   {
       foreach(SomeClass rowData in SomeClasses)
       {
           Rows.Add(rowData.ToStringArray());
       }
   }
} 

But, now I have no way to seperate one set of row data from the next. I could add RowHelper Member public int RowSize. Then the consumer will need to use RowSize to parse the rows. Is that the best way to go about this?

For what it's worth, I am creating a helper class to turn objects into rows that can be inserted into table tr in the View layer of my MVC project.


If you want to "separate one set of row data from the next", simply add an intermediate RowSet class between your RowHelper and your Rows.

class RowSet
{
    public void List<string[]> Rows = new List<string[]>();
}

class RowHelper
{
    public List<RowSet> RowSets;

    public RowHelper()
    {
        RowSets = new List<RowSet>();
    }

    public void CreateRows(SomeClass[] SomeClasses)
    {
        RowSet set = new RowSet();

        foreach(SomeClass rowData in SomeClasses)
        {
             set.Rows.Add(rowData.ToStringArray());
        }

        RowSets.Add(set);
    }
} 

So, RowHelper has a public property which is a collection of RowSet instances.

RowSet contains your list of Rows.

Your CreateRows method can create a new instance of RowSet, populate it with rows and add it to the RowSets property.

You can now iterate over RowHelper.RowSets and from there, iterate over RowSet.Rows.

Consider how you will differentiate between your RowSets and choose a collection class accordingly. For example, if you will simply access them serially, List<RowSet> is fine, but if you'd like to use, say, a named index, consider Dictionary<string,RowSet> instead.


Perhaps you could implement IComparable in SomeClass.

There are lots of examples on how to implement that interface. David Hayden has a blog about it.

class SomeClass : IComparable
{
  ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜