1

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.

leppie
  • 115,091
  • 17
  • 196
  • 297
Simon
  • 1,412
  • 4
  • 20
  • 48
  • If you need your data output in JSON format (i.e. your list of Users and their associated object graphs) you might want to consider using a JSON serializer. Have a look at [Does .NET 4 have a built-in JSON serializer/deserializer?](http://stackoverflow.com/questions/3275863/does-net-4-have-a-built-in-json-serializer-deserializer). – Todd Bowles Jan 14 '14 at 11:53

1 Answers1

1

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.

Raidri
  • 17,258
  • 9
  • 62
  • 65
  • thank you This worked, however, it removed many empty columns, which if im representing within a table, id still need. Managed to get around this by using concat rather than union var aaData = PatList.Select(d => (new string[] { d.Username, d.Address1, d.Age.ToString() }.Concat(d.Columns.Select(c => c.ColumnHeader))).ToArray() ).ToArray(); – Simon Jan 14 '14 at 11:55
  • Yes, `Union` removes duplicate / empty headers. – Raidri Jan 14 '14 at 11:58