Linq- Finding the Same Record Total - linq

In the image below, the total number of times which business is viewed each day is kept. What I want to do is to find the total number of views belonging to the same id number. For example, I want to find the total view value of records whose businessId is 400.
Database Table Image

This will do the work, you may need to adapt some stuff indeed :
var totalViewsByBusinessId = records
.GroupBy(r => r.businessId)
.Select(g => new
{
BusinessId = g.Key,
TotalViews = g.Sum(r => r.views)
});
int businessId = 400;
var totalViews = totalViewsByBusinessId
.FirstOrDefault(g => g.BusinessId == businessId)?.TotalViews ?? 0;
With that, you will get the total amount of views for each business. Then you will just need to use a where to see the total views of the wanted business.

Related

Take one and skip other duplicate item in a child table

I have a list of Items and every item have some list, Now I wants to select Distinct items of child. I have tried like below but it's not working.
var items = await _context.Items.
Include(i => i.Tags.Distinct()).
Include(i => i.Comments).
OrderBy(i => i.Title).ToListAsync();
//Tag items
TagId - tag
------------------
1 --- A
2 --- B
3 --- B
4 --- C
5 --- D
6 --- D
7 --- F
//Expected Result
Item.Tags -> [A,B,C,D,F]
how can I do this in EF Core? Thanks.
You can use the MoreLinq library to get DistinctBy or write your own using this post.
Then use this:
var items = await _context.Items.
Include(i => i.Tags).
Include(i => i.Comments).
OrderBy(i => i.Title).
DistinctBy(d => d.Tags.tag).
ToListAsync();
You want to get distinct records based on one column; so that should do it.
Apparently you have a table of Items, where every Item has zero or more Tags. Furthermore the Items have a property Comments, of which we do not know whether it is one string, or a collection of zero or more strings. Furthermore every Item has a Title.
Now you want all properties of Items, each with its Comments, and a list of unique Tags of the items. Ordered by Title
One of the slower parts of database queries is the transport of the selected data from the database management system to your local process. Hence it is wise to limit the amount of data to the minimum you are really using.
It seems that the Tags of the Items are in a separate table. Every Item has zero or more Tags, every Tag belongs to exactly one item. A simple one-to-many relation with a foreign key Tag.ItemId.
If Item with Id 300 has 1000 Tags, then you know that every one of these 1000 Tags has a foreign key ItemId of which you know that it has a value of 300. What a waste if you would transport all these foreign keys to your local process.
Whenever you query data to inspect it, Select only the properties
you really plan to use. Only use Include if you plan to update the
included item.
So your query will be:
var query = myDbContext.Items
.Where(item => ...) // only if you do not want all items
.OrderBy(item => item.Title) // if you Sort here and do not need the Title
// you don't have to Select it
.Select(item => new
{ // select only the properties you plan to use
Id = item.Id,
Title = item.Title,
Comments = item.Comments, // use this if there is only one item, otherwise
Comments = item.Comments // use this version if Item has zero or more Comments
.Where(comment => ...) // only if you do not want all comments
.Select(comment => new
{ // again, select only the Comments you plan to use
Id = comment.Id,
Text = comment.Text,
// no need for the foreign key, you already know the value:
// ItemId = comment.ItemId,
})
.ToList();
Tags = item.Tags.Select(tag => new
{ // Select only the properties you need
Id = tag.Id,
Type = tag.Type,
Text = tag.Text,
// No need for the foreign key, you already know the value
// ItemId = tag.ItemId,
})
.Distinct()
.ToList(),
});
var fetchedData = await query.ToListAsync();
I haven't tried it, but I'd say you put .Distinct() in the wrong place.
var items = await _context.Items
.Include(i => i.Tags)
.Include(i => i.Comments).
.OrderBy(i => i.Title)
.Select(i => { i.Tags = i.Tags.GroupBy(x => x.Tag).Select(x => x.First()); return i; })
.ToListAsync();

linq avg on grouped counts

Please consider this simple class
public class SEANCE
{
int ID_SEANCE {get;set;}
DateTime SEA_DATE {get;set;}
}
It's for a fitness management app, the SEANCE class is the session table for the members.
Here's my starting query to show the number of the sessions grouped by day Hour
var lst = ctx.SEANCES
.GroupBy(o => o.SEA_DATE.Hour)
.Select(g => new ChartData()
{
DT = new DateTime(2017, 01, 01, g.Key, 0, 0),
VALUE = g.Count()
});
return lst.OrderBy(a => a.DT).ToList();
as you can see, it returns the total number of sessions grouped by hour.
What I want instead is the average number of sessions by day and grouped by hour, and that's where I am a little lost :p
here what i mean
for example at 18, 1500 is corresponding to the total number of sessions at that time.
what i want instead is the average number by day
hope it make sense now :)
ctx.SEANCES.Count() / lst.Count(), but that seems like database source so better to use the result:
var groups = ctx.SEANCES
.GroupBy(s => s.SEA_DATE.Hour)
.OrderBy(g => g.Key)
.Select(g => new ChartData()
{
DT = g.First().SEA_DATE,
VALUE = g.Count()
})
.ToList();
var averageByHour = groups.Average(c => c.VALUE);
var averageByDay = groups.GroupBy(s => s.DT.Day).Average(g => g.Sum(c => c.VALUE));

How to make zero counts show in LINQ query when getting daily counts?

I have a database table with a datetime column and I simply want to count how many records per day going back 3 months. I am currently using this query:
var minDate = DateTime.Now.AddMonths(-3);
var stats = from t in TestStats
where t.Date > minDate
group t by EntityFunctions.TruncateTime(t.Date) into g
orderby g.Key
select new
{
date = g.Key,
count = g.Count()
};
That works fine, but the problem is that if there are no records for a day then that day is not in the results at all. For example:
3/21/2008 = 5
3/22/2008 = 2
3/24/2008 = 7
In that short example I want to make 3/23/2008 = 0. In the real query all zeros should show between 3 months ago and today.
Fabricating missing data is not straightforward in SQL. I would recommend getting the data that is in SQL, then joining it to an in-memory list of all relevant dates:
var stats = (from t in TestStats
where t.Date > minDate
group t by EntityFunctions.TruncateTime(t.Date) into g
orderby g.Key
select new
{
date = g.Key,
count = g.Count()
}).ToList(); // hydrate so we only query the DB once
var firstDate = stats.Min(s => s.date);
var lastDate = stats.Max(s => s.date);
var allDates = Enumerable.Range(1,(lastDate - firstDate).Days)
.Select(i => firstDate.AddDays(i-1));
stats = (from d in allDates
join s in stats
on d equals s.date into dates
from ds in dates.DefaultIfEmpty()
select new {
date = d,
count = ds == null ? 0 : ds.count
}).ToList();
You could also get a list of dates not in the data and concatenate them.
I agree with #D Stanley's answer but want to throw an additional consideration into the mix. What are you doing with this data? Is it getting processed by the caller? Is it rendered in a UI? Is it getting transferred over a network?
Consider the size of the data. Why do you need to have the gaps filled in? If it is known to be returning over a network for instance, I'd advise against filling in the gaps. All you're doing is increasing the data size. This has to be serialised, transferred, then deserialised.
If you are going to loop the data to render in a UI, then why do you need the gaps? Why not implement the loop from min date to max date (like D Stanley's join) then place a default when no value is found.
If you ARE transferring over a network and you still NEED a single collection, consider applying D Stanley's resolution on the other side of the wire.
Just things to consider...

C# Entity Framework and Predicate Builder - Find the Index of a Matching Row within an IQueryable / Pagination Issue

I have a PredicateBuilder expression which returns an IQueryable like so (contrived example):
var predicate = PredicateBuilder.True<CoolEntity>();
predicate = predicate.And(x => x.id > 0);
IQueryable<CoolEntity> results = CoolEntityRepository
.FindBy(predicate)
.OrderByDescending(x => x.id);
I then use this to generate a paginated list containing only the results for a given page using an MVC Index controller for CoolEntity entities like so:
int total = results.Count(); //Used by my controller to show the total number of results
int pageNumber = 2;
int pagesize = 20;
//Only get the entities we need for page 2, where there are 20 results per page
List<CoolEntity> resultList = results
.Skip(pageNumber * pageSize)
.Take(pageSize)
.ToList()
This query ensures that only the relevant results are returned for each page, as there are many thousands of records returned from an SQL database via the repository. It has been working nicely.
The problem is, I now want to be able to find out which of the paginated pages for my Index I would need to return for a particular entity. For example, say one of my CoolEntity objects has an ID of 5 - how could I determine what the value for pageNumber would need to be if I wanted to load the paginated page that that entity would be on for my Index controller?
Specifically, how could I find out that for results, the entity with ID 5 was the 651st row, and consequently use this number to determine pageNumber (i.e. Math.Ceiling(651/pagesize) or something similar)? Is there a better approach to this?
A colleague of mine came up with a solution for this which seems to be very fast.
results
.Select( x => x.id)
.ToList()
.Select((entry, index) => new { ID = entry, Rank = index + 1, PageNumer = ((index+ 1) / pagesize ) + 1 })
.Where(x => x.id== 5)
This found the result from ~100000 records in about 00:00.191 seconds when tested in Linqpad. Please let me know if you have a more efficient way of doing this.

Groupby and where clause in Linq

I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote
var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
.Where(x => x.TripPath.PathNumber == pathnum)
.Select(x => x.TripPath.TripPathLink.Link.Speed).Min();
I am not able to use group by and where together it keeps giving error .
My query should
Select all the values.
filter it through the where clause (pathnum).
Groupby the road Name
finally get the min value.
can some one tell me what i am doing wrong and how to achieve the desired result.
Thanks,
Pawan
It's a little tricky not knowing the relationships between the data, but I think (without trying it) that this should give you want you want -- the minimum speed per road by name. Note that it will result in a collection of anonymous objects with Name and Speed properties.
var data = newTrips.Where(x => x.TripPath.PathNumber == pathnum)
.Select(x => x.TripPath.TripPathLink.Link)
.GroupBy(x => x.Road.Name)
.Select(g => new { Name = g.Key, Speed = g.Min(l => l.Speed) } );
Since I think you want the Trip which has the minimum speed, rather than the speed, and I'm assuming a different data structure, I'll add to tvanfosson's answer:
var pathnum = 1;
var trips = from trip in newTrips
where trip.TripPath.PathNumber == pathnum
group trip by trip.TripPath.TripPathLink.Link.Road.Name into g
let minSpeed = g.Min(t => t.TripPath.TripPathLink.Link.Speed)
select new {
Name = g.Key,
Trip = g.Single(t => t.TripPath.TripPathLink.Link.Speed == minSpeed) };
foreach (var t in trips)
{
Console.WriteLine("Name = {0}, TripId = {1}", t.Name, t.Trip.TripId);
}

Resources