Group-by specific time ranges in LINQ - c#

I have a
List<Advertisement>
where Advertisement contains
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
What I want to do is group the elements in the List<Advertisement> by three specific time ranges using a GroupBy. The three time ranges are as follows:
x => x.StartDate > DateTime.Now.Subtract(TimeSpan.FromDays(1))
x => x.StartDate > DateTime.Now.Subtract(TimeSpan.FromDays(7))
x => x.StartDate > DateTime.Now.Subtract(TimeSpan.FromDays(365))
So elements with start date in the last day, elements with start date in the last week and elements with start date in the last year.
The group of elements from the last year should include those elements with a start date in the last week and day. And the group of elements from the last week should include those elements from the last day.
I just cant seem to think how to do this. Cheers.

As you want each group to also include the previous groups contents (eg lastweek includes last day) I've constructed a union query
var today=items.Where(l=>l.StartDate>DateTime.Now.Subtract(TimeSpan.FromDays(1)));
var lastweek=items.Where(l=>l.StartDate>DateTime.Now.Subtract(TimeSpan.FromDays(7)));
var lastyear=items.Where(l=>l.StartDate>DateTime.Now.Subtract(TimeSpan.FromDays(365)));
var result = today.Select(d => new { Group="Last Day",item=d})
.Union(lastweek.Select(w => new {Group="Last Week",item=w}))
.Union(lastyear.Select(y => new {Group="Last Year",item=y}))
.GroupBy (l => l.Group,l=>l.item);
How this query works is it creates 3 sub queries to select the relevant data.
Each query then uses a select operator to select the match group name and the original item projected into an anonymous object. (Basically creates a new object with the groupname as one property and the original Item as another).
I then use union to combine the multiple results together in one big list. (Union has the added property that it strips duplicates, but there shouldn't be any). Once I have the big list I can then Group by the groupname, the second parameter basically puts the orginal item back in as the group value.

You can create a method (or extension) wich will return some value specific to a group, and then make grouping by it.

One method may be to write an extension method which returns the category that it falls into.
public static int GetCategory(this Advertisement advert)
{
if(x.StartDate > DateTime.Now.Subtract(TimeSpan.FromDays(1)))
{
return 1;
}
etc...
}
then you can group by the GetCategory property. It is probably better to return an Enum instead of an integer.

Related

Is there any way to compare a list object and add specific items

I have a List which contains the order details of several users such as StoreId, OrderTotal, dateModified etc. I want to add the order total which fall under same date but different time.
Below is the code which fetches data from the database. Also I have attached the output which I am getting.
An example of what I am trying to do is: if there are 2 orders for 08/09/2020 then I want to add the orderValue. The third column in the image refers to order value.
public async Task<IActionResult> OnGet()
{
try
{
StoreOrderDetails = new List<Store_Order>();
StoreOrderDetails2 = new List<Store_Order>();
var res = await UOW.CurrentContext.StoreOrder
.OrderBy(x => x.OrderModified)
.ToListAsync();
foreach (var item in res)
{
if(item.Status.ToString() == "PaymentComplete" &&
item.StoreId == defaultStoreId)
{
StoreOrderDetails.Add(item);
}
}
totalCount = StoreOrderDetails.Count();
StoreId = defaultStoreId;
StoreOrderDetails.GroupBy(x => x.OrderModified).Select(grpData =>
new Store_Order
{
OrderModified = grpData.Key,
OrderTotal = grpData.Sum(item => item.OrderTotal),
});
}
catch
{
}
return Page();
}
If that first column in your image is the date you refer to in code when you say x => x.OrderModified, you'll need to group by only the date element, excluding the time:
StoreOrderDetails.GroupBy(x => x.OrderModified.Date).Select(grpData =>
^^^^^
When you group a date that has a time too, then events will go into different groups if they are even only a nanosecond different. If you want dates to group according to the day all different things happened on, then you have to group by the date without the time. The easiest way to do this is to ask for a DateTime's Date property - it's the date, but with the time of midnight. If you fake it as if all orders occurred at midnight, then the Sum will work out
Oh, and you'll actually need to store/use the results of the group operation...

Determining Date Overlapping in a list of dates

I have a list of items that each have a start and end date time component.
var myDates= new List<Tuple<DateTime, DateTime>>();
Which I fill it out with some date.
Now I wanted to loop through them and see if any two of those have any overlapping date rang. So I did this:
var myOverlapList = (from start in myDates
from endDate in myDates
where !Equals(start, end)
where start.Item1 <= end.Item2 && start.Item2 >= end.Item1
select end);
It works when dates have overlap for example one day back and forth between two dates BUT it does NOT work when two date entries have the EXACT SAME values.
So how I can fix my code or just something else to achieve that.
The
where !Equals(startDate, endDate)
line, which is supposed to filter out the same date tuple actually is filtering out any duplicate, so any matching timespan falls out of the selection. So your query will return all DateTime tuples, which overlap with some other tuple in the collection, but only unique. And you want also to return tuples if they encounter in your collection more then once.Your problem, actually is that you can not differentiate between two different items with the same value. So you need a discriminator for them and because you use a list, the index of an item fits well. You can cast your Tuple<DateTime, DateTime> collection into, e. g. {int id, Tuple<DateTime, DateTime> range} object by
var datesWithId = dates.Select((d, i) => new {id = i, range = d});
and then modify your query like this:
var anyOverlap = (from startDate in datesWithId
from endDate in datesWithId
where startDate.id!=endDate.id
&& startDate.range.Item1 <= endDate.range.Item2
&& startDate.range.Item2 >= endDate.range.Item1
select endDate.range).Distinct();

How to filter list that has date and retrieve only data within 7 days

So I have this model:
Student Model
public int StudentId {get; set;}
public string StudentName {get; set;}
public DateTime EnrollDate {get; set;}
I also have a list of student Model which is something like
List<Student> listOfStudents = new List<Student>();
and inside that list there are 100 students detail and the enroll date.
What I do next is to sort the list into showing from the latest one to the oldest one.
listOfStudents.Sort((x, y) => DateTime.Compare(y.EnrollDate, x.EnrollDate));
and it's working. However, I am currently struggling in showing only the EnrollDate within 7 days from Today.
Conceptually, I think of LINQ a lot like SQL. You have the SELECT portion, which is your projection (i.e. what am I pulling out of this set of data?). If you omit the Select() clause from LINQ, you'll get the whole record vs. only a portion if you wanted to pluck out only pieces of it. You have your WHERE portion which is a limiter, or filter condition that when applied to the set pulls back only the records that satisfy said condition. And lastly, there are operations you can apply that affect the order of the returned set. That's where the OrderBy() and OrderByDescending() come into play. So lets map those concepts to the examples below
No Select(), but we do have a Where() and an OrderBy()
var then = DateTime.Now.AddDays(-7); //One portion of our Where. More below
var sortedStudents = listOfStudents
//Our predicate. 's' = the Student passed to the function. Give me only the students
//where s.EnrollDate is greater or equal to the variable 'then' (defined above)
.Where(s => s.EnrollDate >= then)
//We have no Select statement, so return whole students
//And order them by their enrollment date in ascending order
.OrderBy(s => s.EnrollDate);
When run, sortedStudents will be loaded up only with students (entire Student objects, not a projection) that meet our Where() criteria. The Where() function takes predicate that specifies our criteria. A predicate is simply a function that accepts a record from the set that we're filtering, and returns a bool indicating whether or not it should be included.
Let's change the filter by adjusting the Where()
//Notice we've changed 'then' from 7 days ago to a fixed point in time: 26 June 2018
var then = new DateTime.Parse("26 June 2018");
var sortedStudents = listOfStudents
.Where(s => s.EnrollDate >= then)
//Still no Select(). We'll do that next
.OrderBy(s => s.EnrollDate);
Just like before sortedStudents will have whole Student records, but this time it will only contain those enrolled after or on 26 June 2018, as specified by our predicate.
Let's add a Select()
var then = new DateTime.Parse("26 June 2018");
var dates = listOfStudents
.Where(s => s.EnrollDate >= then)
.Select(s => s.EnrollDate);
Now we've changed it so that instead of pulling back a whole Student we're only plucking out the EnrollDate. Notice I've changed the name of the receiving variable from sortedStudents to dates reflecting the fact that it now only contains a list of DateTime objects.
You could still replace .OrderBy() with .OrderByDescending() to change the order.
How about breaking down the problem into 2 sub-problems?
Sub-problem #1
showing only the EnrollDate within 7 days from Today
We only need Students whose EnrollDate property is within 7 days from today:
var today = DateTime.UtcNow;
sevenDaysOldList = listOfStudents.Where(x => (today - x.EnrollDate).TotalDays < 7);
The subtraction of the two dates results in a TimeSpan with a TotalDays property, which we can use to determine the number of days elapsed between the two dates.
Sub-problem #2
sort the list into showing from the latest one to the oldest one.
We need to sort sevenDaysOldList by EnrollDate in descending order:
sevenDaysOldList.Sort((x, y) => y.EnrollDate.CompareTo(x.EnrollDate));
..which will sort the list in place. OrderByDescending is a good candidate for this (it returns a new ordered list implementing IOrderedEnumerable<T>):
sevenDaysOldList.OrderByDescending(x => x.EnrollDate);
// and of course .OrderBy(x => x.EnrollDate) for ascending order
Combine #1 & #2
You can now combine the solutions of the two sub-problems into one. How you do it is at your own discretion. This is how I would do it:
var sevenDaysOldList = listOfStudents.Where(x => (today - x.EnrollDate).TotalDays < 7)
.OrderByDescending(x => x.EnrollDate);
Update: question in comment
How do I modify/sort the list that remove all the list less than "26 June 2018" ? So the list will only have data date greater than 26 June 2018. Any data with date before 26 June will be removed
You can initialize that date in a DateTime variable, and use it with List<T>.RemoveAll(Predicate<T>), to remove items in sevenDaysOldList which are smaller than that date:
var filterDate = new DateTime(2018, 06, 26);
sevenDaysOldList.RemoveAll(x => x.EnrollDate < filterDate);

LINQ: Group by date including the year

I have dataset looks like this:
FileName Date
ABC - 01/10/16
DBC - 01/11/16
ZYX - 03/10/16
ABX2 - 01/10/17
IOS - 01/09/17
How can I group them into a list of groups of months while ensuring that the year is taken into account in the clause?
I'm currently using a LINQ Query is creating groups by month but not including the year, so I have a group of ABC, ZYX and ABX2. even though ABX2 was a 2017 report but the same month so should be in a different group.
I've been trying different ways of doing this but none of have been successful as of yet.
var newList = from x in list
group x
by x.Properties.LastModified.Value.Month into lastMod
where lastMod.Count() > 1
select lastMod;
Once I have them in separate groups, I will find out which one was written last and save that and remove the rest. I'm quite stuck and been on this issue for half day. would appreciate fresh eyes on it.
You can group by a composite year-month key, like this:
var newList = list
.Where(x => x.Properties.LastModified.HasValue)
.GroupBy(x => new {
x.Properties.LastModified.Value.Month
, x.Properties.LastModified.Value.Year
})
.Where(g => g.Count() > 1);
You need to ensure that LastModified has non-null value before accessing its Value property.
I can't test this at the moment but I think grouping by an anonymous type that contains both the month and year should do it.
var newList = from x in list
group x
by new {x.Properties.LastModified.Value.Month, x.Properties.LastModified.Value.Year} into lastMod
where lastMod.Count() > 1
select lastMod;

Linq query for below data

id vid Amount Date
a 1 10 Today
a 1 5 Yesterday
b 2 6 Today
b 2 7 Yesterday
How to fetch records using linq where amount for today is greater than yesterday for each vid group bi Id and vid?
If I have understood correctly, you have a class that looks like this:
class Data
{
public string Id;
public int Vid;
public int Amount;
public DateTime Date;
}
And an enumeration of instances of this class, which contains multiple instances that share the same Vid value, but different Amount and Date values. What you want is to get all instances which simultaneously have the greatest Date and Amount values of all other instances with the same Vid. Once you have that, you want to group the results by Id and Vid
In this case, you want the following query:
var myList = new List<Data>();
var result = myList.SelectMany(d1 => myList.Where(d2 => d2.Vid == d1.Vid && d1.Amount < d2.Amount && d1.Date < d2.Date)).OrderBy(data => data.Vid).ThenBy(data => data.Id).ToList();
What we are doing here is the following:
Iterate through all elements in myList.
For each element, find all other elements with the same Vid, but a larger Date and Amount.
Flatten all results into a single collection using SelectMany.
Order the resulting enumeration by Vid, and then by Id.
Convert the result into a list.

Categories

Resources