Simon
Simon

Reputation: 1476

Create array from nested lists

A little difficult to explain, but here goes... (using .net 4.5, C#)

We currently have a list of items ( as per below "User") which contains a list of column objects. ie.

 public class TableColumn
{
    public string ColumnHeader { get; set; }
    public string ColumnValue { get; set; }
    public int ColumnWidth { get; set; }  
}

public class User
{
    public string Username { get; set; }
    public string Address1 { get; set; }
    public int Age { get; set; }

    public List<TableColumn> Columns { get; set; }
}

We are working with JQGrid where we are required to pass back Json.

without the nested list we would use :-

var aaData = PatList.Select(d => new string[] { 
              d.Username ,
              d.Address1 ,
              d.Age}).ToArray();

 return Json(new
        {
            sEcho = param.sEcho,
            aaData = aaData,
            iTotalRecords = Convert.ToInt32(totalRowsCount.Value),
            iTotalDisplayRecords = Convert.ToInt32(filteredRowsCount.Value)
        }, JsonRequestBehavior.AllowGet);

which works great.

What we are struggling with is how to add in the list of columns.

   var aaData = PatList.Select(d => new string[] { 
              d.Username ,
              d.Address1 ,
              d.Age,
              d.Columns.forEach(????)}).ToArray();

so the columns are related to a user.

Hopefully that makes sense. Any assistance would be appreciated.

Upvotes: 1

Views: 1456

Answers (1)

Raidri
Raidri

Reputation: 17550

You can do something like this:

var aaData = PatList.Select(d => (new string[] { 
        d.Username,
        d.Address1,
        d.Age.ToString()
    }.Union(d.Columns.Select(c => c.ColumnHeader))).ToArray()
).ToArray();

This generates for every User in PatList an array with Username, Address1, Age & all ColumnHeaders.

Upvotes: 1

Related Questions