Reputation: 15
I want to split my row into few columns i have data:
A - 21 - PL - 21 - OFF
A - 22 - PL - 22 - OFF
B - 1 - DE - 1 - Green
B - 2 - DE - 2 - Green
C - 30 - ES - 30 - Orange
C - 31 - ES - 31 - Orange
D - 1 - TH - 1 - RED
D - 2 - TH - 2 - RED
That data show for me as List (just in one column all data step by step) and i can't groupby "Name" but i want to split it into columns:
Coulmn1: A-21-PL-21-OFF | Column2: B - 1 - DE - 1 - Green | coulmn3: C - 30 - ES - 30 - Orange
Here's my code for generate View where i want get columns with data grouped by name:
public ActionResult PosList()
{
List<StanowiskoVM> devicesList;
using (Db db = new Db())
{
devicesList = db.Stanowisko.ToArray().Select(x => new StanowiskoVM(x)).ToList();
}
return View(devicesList);
}
here's my variables in ViewModel:
public int Id { get; set; }
public string Name { get; set; }
public string Country{ get; set; }
And i get my View of List what i get from database to VM:
@foreach (var item in Model) {
<tr>
<td>
Name: @Html.DisplayFor(modelItem => item.Nazwa) + Kraj: @Html.DisplayFor(modelItem => item.Kraj) + @Html.DisplayFor(modelItem => item.AktualnyStan)
</td>
</tr>
Now i need split it on the new columns when item.nazwa == "A"...
Upvotes: 1
Views: 577
Reputation: 34443
This isn't trivial since the number of items in each column may be different. You need to create a Pivot table.
See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] inputs = {
"A - 21 - PL - 21 - OFF",
"A - 22 - PL - 22 - OFF",
"B - 1 - DE - 1 - Green",
"B - 2 - DE - 2 - Green",
"C - 30 - ES - 30 - Orange",
"C - 31 - ES - 31 - Orange",
"D - 1 - TH - 1 - RED",
"D - 2 - TH - 2 - RED"
};
var uniqueNames = inputs
.Select(x => new { key = x.Split(new char[] {'-'}).First().Trim(), name = x})
.GroupBy(x => x.key)
.OrderBy(x => x.Key)
.ToArray();
DataTable dt = new DataTable();
foreach (var name in uniqueNames)
{
dt.Columns.Add(name.Key, typeof(string));
}
int maxRows = uniqueNames.Max(x => x.Count());
for(int row = 0; row < maxRows; row++)
{
DataRow newRow = dt.Rows.Add();
for(int col = 0; col < uniqueNames.Count(); col++)
{
if(row < uniqueNames[col].Count())
{
newRow[col] = uniqueNames[col].Skip(row).First().name;
}
}
}
}
}
}
Upvotes: 1
Reputation: 4260
You can try LINQ
var mylist = new List<string> { "A", "A", "B", "B", "B", "C", "C", "D" };
var result = mylist.GroupBy(x => x)
.Select(x => x.OrderBy(x => x).Take(1))
.SelectMany(x => x)
.ToList();
Upvotes: 1