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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With