Home > Mobile >  c# Is there any way to do a loop within defining a List<Cell>?
c# Is there any way to do a loop within defining a List<Cell>?

Time:09-26

I am new to working with smartsheets via c# and I am currently working on doing some updates within the api. In order to do this, I create a row and then inside the row I define a list of cells. My goal is to be able to loop through a data table to dynamically add as many cells into the row as there are in the datatable, instead of writing them out (as in the first example). First, here is a copy of what the code looks like to update 2 cells:

            Row rowA = new Row
        {
            Id = 2723423424224,
            Cells = new List<Cell>
            {
                new Cell{
                    ColumnId = 999999999399108,
                    Value = "TESTING WORKED WOOHOO!!!!",
                },
              new Cell
              {
                  ColumnId = 5345345435439108,
                    Value = "TESTING WORKED WOOHOO!!!!",
              }
            }       
        };

This would essentially update 2 columns for a row.

This is what I'm trying to do (however I don't think I can because when I put in the foreach loop it was showing errors). But if someone could give me direction on a way to achieve this goal that'd be awesome.

            Row rowA = new Row
        {
            Id = 2723423424224,
            Cells = new List<Cell>
            {
           foreach (datarow dr in datatbl)
            {
             ColumnId = /*data table value*/;
             Value = /*data table value 2*/ ;

            }

            }       
        };

However when I write the code like this, it does not like the foreach loop. I'm assuming you cannot do that type of thing in the definition of the cell list, i'm just not familiar with it at all. Was hoping to get some insight on if it's possible to dynamically add cells to the Cell list definition.

CodePudding user response:

I would try this:

var rowA = new Row
{
    Id = 2723423424224,
    Cells = datatbl.Rows.OfType<DataRow>().Select(_=> new Cell { ColumnId = _.Field<int>("ColumnId"), Value = _.Field<string>("Value")}).ToList()

};

CodePudding user response:

Define it first, then add it.

        Row rowA = new Row
        {
            Id = 2723423424224,
            Cells = new List<Cell>()  
        };

        foreach (datarow dr in datatbl)
         {
            rowA.Cells.Add(new(){
           ColumnId = /*data table value*/;
           Value = /*data table value 2*/ ;
           })
          }

CodePudding user response:

You're looking for something like this:

Row rowA = new Row
{
    Id = 2723423424224,
    Cells =
        datatbl
            .AsEnumerable()
            .Select(dr =>
                new Cell()
                {
                    ColumnId = dr.Field<long>("ColumnId"),
                    Value = dr.Field<string>("Value"),
                })
                .ToList()
};
  • Related