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;
Related
I've read the many related questions but can't find this exactly.
I'm trying to adjust the ordering on an OLD .NET (4.0) web page so it shows events that are upcoming ASC (showing closest in the future first), followed by events in the past showing them DESC in a single list that is skipped to take a 'page' of results.
So like this:
Event 1 - tomorrow
Event 2 - in a week
Event 3 - in a month
Event 4 - yesterday
Event 5 - a week ago
Event 6 - a month ago
The current function grabs the list and does a sort, skip and take (a single page):
// Currently this creates a single list order by date desc
var numToLoad = 20;
var list = _context.AllItems.Where(i => i.typeTitle == source);
var items = list.OrderByDescending(i => i.dateCreated).Skip((pageNum - 1) * numToLoad).Take(numToLoad);
I have tried making two lists, ordering each appropriately, and then concatenating them, but then I can't do a skip, as that requires a sorted list.
// We need a single list but with upcoming dates first, ascending, then past dates descending
var dateNow = DateTime.Now;
var listFuture = _context.AllItems.Where(i => i.typeTitle == source && i.dateCreated >= dateNow).OrderBy(i => i.dateCreated);
var listPast = _context.AllItems.Where(i => i.typeTitle == source && i.dateCreated < dateNow).OrderByDescending(i => i.dateCreated);
var listAll = listFuture.Concat(listPast);
var itemsAll = listAll.Skip((pageNum - 1) * numToLoad).Take(numToLoad); // <-- this gives an error as it's not sorted
So I don't have to rewrite all the code that handles the returned list (pagination etc) I'd really like to be able to return a single list from the function!
I did see that it might be possible to do conditional sorting, then do the skip and take in a single linq but I just can't get anything like that to work.
Any ideas?
The problem here is that .Concat() of two queries loose ordering when translated to SQL (you cannot to UNION two queries with different order each).
If you are using MSSQL, you can use ordering like that:
var dateNow = DateTime.Now;
var query = _context.AllItems
.Where(i => i.typeTitle == source)
// future items first
.OrderBy(i => i.dateCreated >= dateNow ? 0 : 1)
// items which closer to now first
.ThenBy(i => Math.Abs(System.Data.Entity.SqlServer.SqlFunctions.DateDiff("day", dateNow, i.dateCreated).Value));
var list = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
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);
I am working on web api with Entity framework as object-relational mapping (ORM) framework for ADO.NET. I need to write a linq query which should return most recent 5 zones traveled by a person.
My table with respective columns is depicted in the attached image. I am using azure sql database as my back-end storage, from the above data i need to get top 5 zone_id list as [4,2,3,2,1] by using linq query. client may request to get zones list with in specific range of stime.
Not 100% sure what you are asking but to get the list of zone-Id would be something like:
var zoneIds = data.Select(z => z.zone_id).Distinct();
This will get you the individual zone ids. (The distinct removes duplicate zone id entries).
If you want to filter by date it would be something like:
var zoneIds = data.Where(z => z.stime > [lowerDateTimeBound] && z.stime < [upperDateTimeBound]).Select(z => z.zone_id).Distinct();
For most recent 5 I would use:
var zoneIds = data.OrderByDescending(z => z.stime).Select(z => z.zone_id).Distinct().Take(5);
If you want to get all zones without removing duplicates remove the .Distinct() call. And to get more result change the Take(x) number. Result should be as follows:
[1, 2, 3, 4] // With distinct
[1, 1, 2, 2, 3] // Without distinct
UPDATE: based on your comments.
Use this to get the list of zone Ids:
var zoneIds = data.OrderByDescending(z => z.stime).Select(z => z.zone_id).ToList();
var zoneIdsArray = zoneIds.ToArray();
for(int c = 1; c < zoneIdsArray.Count(); c ++)
{
if (zoneIdsArray[c].zone_id == zoneIdsArray[c-1].zone_id)
{
zoneIds.Remove(zoneIdsArray[c]);
}
}
var last5Zones = zoneIds.Select(z => z.zone_id).ToList().Take(5);
The resulting last5Zones list should have the correct list of last 5 zones (according to what I think you are looking for from your comments)
Your question is unclear about what the expected result is. You state that you want the 5 most recent zones the person traveled in, which, according to your picture should result in [4,2,3,3,2] however you state the result should be [4,2,3,2,1] which is not in chronological order.
Nevertheless, the LINQ statement you would use to filter the data by the record's 5 most recently traveled zones would be:
int[] mostRecentZones = _ctx.OrderByDescending(x=>x.stime).Take(5).Select(x=>x.zone_id).ToArray();
Assuming '_ctx' is the name of you DBContext object and 'stime' is a DateTime object and 'zone_id' is an integer field.
I couldn't express better what I am asking in the title.
This is what I'm looking.
I have a disordered List of an Specific Object I have a DateTime and String Property.
The String Property Has values Like this ones (note that it is an string, not a number, it always has the K letter, I should be ordering with just the numbers):
K07000564,
K07070000
K07069914
K07026318
K07019189
What I want is to order the List By Date... but when ordering if the String value is present in the collection with other Date I want to order them just after this one (By Date also in that miniGroup of IdFinders)... and then keep ordering...
Something Like this:
Edit
I edited the example to clarify that ordering by IdFinder will not work... I need to order By Date.. if when ordering by Date the IdFinder is present more than once in the collection should show them just after this last one, and then keep ordering the rest of them and so on by each idfinder
ID Date
**K07000564** Today
K07000562 Yesterday
K07000563 The Day Before Yesterday
**K07000564** The day before the day before yesterday
Should be
K07000564 Today
K07000564 The day before the day before yesterday
K07000562 Yesterday
K07000563 The Day Before Yesterday
I achieved this in SQL Server 2008 in a project before with something like this:
WITH B
AS
(
SELECT
ID,
MAX(DATE_COLUMN) DATE_COLUMN,
ROW_NUMBER() OVER (ORDER BY MAX(DATE_COLUMN) DESC) RN
FROM MYTABLE
GROUP BY ID
)
SELECT *
FROM MYTABLE c
, B
WHERE ID= b.ID
ORDER BY b.rn, c.DATE_COLUMN desc;
But I'm not good with Linq and I have no idea of how doing this in Linq.
Maybe an Important Note I'm in .NEt 2.0, so no LINQ available but I'm using Linqbridge to use Linq.
I tried this, but as you will notice, this will not work
oList.OrderBy(i => i.IdFinder).ThenByDescending(i => i.OperationDate);
I hope to have explained this clearly
var result = oList.OrderByDescending(x => x.OperationDate)
.GroupBy(x => x.IdFinder)
.SelectMany(x => x);
I think this should do the trick:
var sortedList = oList
.GroupBy(x => x.IdFinder)
.Select(g =>
new
{
MaxOpDate = g.Max(x => x.OperationDate),
Items = g
})
.OrderByDescending(g => g.MaxOpDate)
.SelectMany(g => g.Items.OrderByDescending(x => x.OperationDate));
However, I haven't tested it with Linqbridge.
Try this
oList.OrderBy(i => int.parse(i.IdFinder.Substring(1,i.IdFinder.Length-1)).ThenByDescending(i => i.OperationDate);
First extract the numeric value out of IdFinder, the orderby this value.
Note -> It is assumed that i.IdFinder is always a valid "K######" where # is number less than Int32.MaxValue.
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.