In my ASP.NET Project I have a data table named BrowserStats which contains different browser list for different users.
I want to group the users by their id and shows the number of access with specific browsers(Chrome,Firefox,IE) using linq.
My Data Table(BrowserStats) is as following:
UserId | Browser ---------------------------- 1 | Chrome-32.0 1 | Chrome-30.0 1 | Chrome-33.0 1 | Firefox-20.0 1 | Firefox-26.0 1 | Safari 1 | IE-9 1 | IE-10 2 | Chrome-31.0 2 | Chrome-32.0 2 | IE-10 2 | Firefox-22.0 2 | Firefox-26.0
My Output Table should be :
UserId | Chrome | Firefox | IE | Others ----------------------------------------------- 1 | 3 | 2 | 2 | 1 2 | 2 | 2 | 1 | 0
- How would be the query in linq for this output?
- Is linq a faster way or I should write a stored procedure with this query in database and call it from C#?
- Is there any good tutorial on Advanced linq queries?
if you want to go with LINQ. it dynamic add column and row to datatable. output is datatable format
output:
first off, I would consider LINQ slow. LINQ is pretty much a clean way to nest array iteration logic. Only use when the CPU must manipulate static data. or data is CPU generated and there is no backing storage.
that's how I think of it anyways. now for the answer:
I have built a database in SQLServer 2012 Express for Demon-Striation purposes (<- Xanth reference). I used your browsers and made imaginary users. the pivot code should be a stored procedure you call from c#. if you are using VS I can edit for a pure VS(2012) solution because I would prefer to use datasets and add a query to the TableAdapter for using a stored procedure. but this should get you 2/3rds the way there
the User Table::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
the Browser Table:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
the Usage Table Sample (324 row total):::::::::::::::::::::::::::::::::::::::::::::::::::
the Diagram:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
The PIVOT (I added this as a stored procedure):::::::::::::::::::::::::::::::::::::::::::
VS 2012 / WPF implementation::::::::::::::::::
after adding the stored procedure, connecting VS to your database, and adding a Dataset to your project. Drag and drop the stored procedure into your dataset. you can also use the stored procedure without the typed dataset generator. See Here
WPF XAML::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
.cs::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
WPF WINDOW:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
(the UserID column defaults to the right most column the select statement could be
select p1.UserID,p1[1],... p.[n]
)You can use Nested group in LINQ:-
I have Used the following Type:-
Here is the working Fiddle.