Felipe Oriani
Felipe Oriani

Reputation: 38598

Converting rows in Columns

I am developing an asp.net mvc application with NHibernate and I have a query where I would like to know how can I convert rows in columns?

I have a dynamic system with a model like this:

// It's a kind of metadata
public class Field
{
   public virtual long Id { get; set; }
   public virtual string Name { get; set; }
}

// the value is here with respective field
public class FieldValue
{
   public virtual long Id { get; set; }
   public virtual Field Field { get; set; }
   public virtual string Value { get; set; }
}

I would like to know how can I get a result where columns are the Field objects and values are FieldValue objects, should I create a ViewModel? or a way to do it with asp.net mvc?

I can do a query to get a result like this:

enter image description here

But I would like to do a query like this (or a way to create a result on my View on the asp.net mvc):

enter image description here

Thanks

Upvotes: 0

Views: 1409

Answers (2)

Tommy
Tommy

Reputation: 39807

I think you are going to need to get fancy/familiar with GroupBy(). If you Group By the Field, you "group" all the values for a field then move to the next one. The pseudo-code would be something like the following

@model IEnumerable<FieldValue>

foreach(var fields in Model.GroupBy(x=>x.Field.Name){
    <h2>fields.key</h2>
    <ul>
        foreach(var fieldValue in fields){
             <li>@fieldValue.Value</li>
        }
    </ul>
}

This should render something like

Field 1

  • some value 1
  • some value 2

Field 2

  • some value 3
  • some value 4

etc.

By using this approach, you can control the formatting however you want to get the desired output.

Upvotes: 1

Vinoth
Vinoth

Reputation: 2439

Not clear with the question. if you want to transform rows into columns - you can use pivot. But i would suggest instead of operating on resultset to transpose, let it return the transposed result set. I meant handle the conversion of rows into columns in your query itself

Upvotes: 0

Related Questions