Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange Table Data using Linq

Tags:

c#

.net

linq

I have data in the following format:

(Table: Hours)
{ Date = "21/04/2008", Person = Sally, Hours= 3 }
{ Date = "21/04/2008", Person = Sam, Hours = 15 }
{ Date = "22/04/2008", Person = Sam, Hours = 8 }
{ Date = "22/04/2008", Person = Sally, Hours = 9 }

Datatypes: Date = Date, Person = String, Hours = Integer

Using LINQ I would like to select it into this format:

{ Date = "21/04/2008", Sam = 15, Sally = 3 }
{ Date = "22/04/2008", Sam = 8, Sally = 9 }

Datatypes: Date = Date, Sam = Integer, Sally = Integer

Is this possible?

like image 927
Reafidy Avatar asked Aug 16 '15 04:08

Reafidy


People also ask

How to query DataTable using LINQ in Java?

To query datatable using linq we call the AsEnumerable () method of the DataTable .Calling this method on the DataTable returns an object which implements the IEnumerable<T> interface.Now we can perform LINQ queries on this object. Add a reference to the System.Data.DataSetExtensions.This is usually added by default.

How do you use LINQ to transform data?

It is also a powerful tool for transforming data. By using a LINQ query, you can use a source sequence as input and modify it in many ways to create a new output sequence. You can modify the sequence itself without modifying the elements themselves by sorting and grouping.

How to separate the values as properties or entities using LINQ?

Using anonymous method and try to separate the values as properties or entities. Now query the above result using LINQ. By using anonymous method secrete the values. Now using LINQ, query the data as you want.

What is LINQ in SQL Server?

Language-Integrated Query (LINQ) is not only about retrieving data. It is also a powerful tool for transforming data. By using a LINQ query, you can use a source sequence as input and modify it in many ways to create a new output sequence.


1 Answers

from d in data
group d by d.Date into g
select new {Date = g.Key, People = g.Select(gg=>new{Person = gg.Person, Hours = gg.Hours})}

This will give you the data, then it's just formatting to display properly.

like image 65
AD.Net Avatar answered Oct 19 '22 17:10

AD.Net