Show values in descending order by date - c#

I have c# list of data returning 2 dates.
5/31/2016 4:34:41 AM
5/31/2016 4:38:08 AM
I am using lambda expression to sort them to show latest date on top. But still its showing wrong. What may be the issue.
var rowEntities =
MyOperations.GetEntitiesByDate().ToList().OrderByDescending(i=>i.JobStartTime);
public DateTime JobStartTime { get; set; }

Try
var rowEntities = MyOperations.GetEntitiesByDate().OrderByDescending(i=>i.JobStartTime).ToList();

var rowEntities = MyOperations.GetEntitiesByDate().ToList().OrderByDescending(i=>i.JobStartTime);
or
var rowEntities = (from dates in MyOperations.GetEntitiesByDate() orderby dates.jobstarttime select dates).Tolist();
or
var rowEntities = (from dates in MyOperations.GetEntitiesByDate() orderby dates.jobstarttime ascending or descending select dates).Tolist();

Related

Take() takes different values than Skip() skips

I have written two different queries, the first one is supposed to get the first 5 objects, and then the next one is supposed to get the next 5 objects ordered by the purchased value. The problem is that the two values in the middle are the same and when I take the first five objects, and then skip the first five objects and take the next five objects the last object of the first set is the same as the first value of the second set and the object with the same purchased value as this object is never shown. My queries are below.
var query = (from v in db.VideoGames
where v.gamesystem == "PC"
orderby v.purchased descending
select v).Take(5);
var query2 = (from v in db.VideoGames
where v.gamesystem == "PC"
orderby v.purchased descending
select v).Skip(5).Take(5);
I would like to know if there is something that I can do differently to keep this from happening.
Edit: I feel that my explanation may be a little confusing so I am going to add an example given 10 VideoGame objects in a database and there purchased value.
VideoGame1.purchased = 1,
VideoGame2.purchased = 2,
VideoGame3.purchased = 3,
VideoGame4.purchased = 4,
VideoGame5.purchased = 5,
VideoGame6.purchased = 5,
VideoGame7.purchased = 7,
VideoGame8.purchased = 8,
VideoGame9.purchased = 9,
VideoGame10.purchased = 10
Here is what I am receiving
query: VideoGame10, VideoGame9, VideoGame8, VideoGame7, VideoGame5
query2: VideoGame5, VideoGame4, VideoGame3, VideoGame2, VideoGame1
Here is what I want
query: VideoGame10, VideoGame9, VideoGame8, VideoGame7, VideoGame6
query2: VideoGame5, VideoGame4, VideoGame3, VideoGame2, VideoGame1
I do not care if I get VideoGame5 in the first query, just as long as I get both the VideoGame5 object and the VideoGame6 object.
the object with the same purchased value as this object is never shown
It did not click till I read this sentence a few times. Assuming you mean you have data like the following
class Videogames
{
public string Name { get; set; }
public int purchased { get; set; }
public string gamesystem { get; set; }
public Videogames(string name, int purchased)
{
Name = name;
this.purchased = purchased;
gamesystem = "PC";
}
}
static void Main(string[] args)
{
var VideoGames = new List<Videogames>();
VideoGames.Add(new Videogames("A", 1));
VideoGames.Add(new Videogames("B", 2));
VideoGames.Add(new Videogames("C", 2));
VideoGames.Add(new Videogames("D", 3));
var query = (from v in VideoGames
where v.gamesystem == "PC"
orderby v.purchased descending
select v).Take(2);
var query2 = (from v in VideoGames
where v.gamesystem == "PC"
orderby v.purchased descending
select v).Skip(2).Take(2);
}
You are getting results like A, B and B, D...
The problem is you do not have deterministic sorting, when there is a tie it is up to whatever underlying system is performing the orderby (likely SQL server, and this is EF or Similar).
To fix this you must make your sorting system more specific so there is no ambiguous ties for the sorting engine to decide for you.
Changing your queires to
var query = (from v in VideoGames
where v.gamesystem == "PC"
orderby v.purchased descending, v.Name ascending
select v).Take(2);
var query2 = (from v in VideoGames
where v.gamesystem == "PC"
orderby v.purchased descending, v.Name ascending
select v).Skip(2).Take(2);
would fix it. You did not show your model so I had to make up a field Name. In database situations you usualy have some kind of primary key ID field, just make your queries sort by the primary key as the last sorting parameter and you should be fine.

linq-to-sql grouping anonymous type

I have a table the contains appointments. These appointments have different statuses (byte from 1 to 5) and dates; the column for the date is simply called AppointDate. I pass in a list of IDs and I want to group the result based on the status AND whether the date of the appointment is past or not.
TheIDs is a list of longs that's passed in as the parameter. This is what I have so far:
var TheCounterInDB = (from a in MyDC.Appointments
where TheIDs.Contains(a.ID)
group a by a.AppointStatus into TheGroups
select new {
TheStatus = TheGroups.Key,
TheTotalCount = TheGroups.Count(),
TheLateCount = ?,
ThePendingCount = ?
}).ToList();
Basically, I want TheLateCount to be the count of all the appointments where status is 1 AND the date is past and ThePendingCount to be the count where status is 1 AND the date is not past. My anonymous type is good to return the count of all the different statuses (that's where the .Key is) but I'm wondering how to best add the date requirement into the grouping.
Thanks for your suggestions.
var TheCounterInDB = (from a in MyDC.Appointments
where TheIDs.Contains(a.ID)
group a by a.AppointStatus into TheGroups
select new {
TheStatus = TheGroups.Key,
TheTotalCount = TheGroups.Count(),
TheLateCount = TheGroups.Count(x => x.AppointStatus == 1 && x.AppointDate < DateTime.Today),
ThePendingCount = TheGroups.Count(x => x.AppointStatus == 1 && x.AppointDate >= DateTime.Today)
}).ToList();

LINQ Groupby a Date in a List of Object

I have a List of the following object :
public class Item
{
public DateTime DliveryDate { get; set; }
public String Order { get; set; }
}
How can i group this List<Item> by Date using LINQ?
I used the following query but didn't got excepted result in a group by dates Got a List object with a junk date of 0001/1/1
var r = from i in Items
group i by i.DliveryDate into s
select s;
This should return what you need:
var listdategroup = from x in psrAlertLogItems.AsEnumerable<Item>()
group x by x.DliveryDate.Date into s
select s;
Maybe your ChangeDateTime contains hour/time information , you should do
var listdategroup = from i in psrAlertLogItems
group i by i.DliveryDate.Date into s select s;
to get only the day component of your datetime
May be this can help u..
var sorted_lists = from sort in lists
group sort by sort.DateInfo into sorted
select sorted;
I'm getting the correct result..
have you tried it using the extension method
var itemsGruopedByDate = Items.GroupBy(item => item.DliveryDate ).ToList();
Just an alternative.
I hope its of any use.
Cheers.

linq goup by day

I have the following grouping statement:
var test = from a in MyDC.Table
where .....
group a by a.Date into daygroups
select new MyModel()
{
TheCount = (from c in daygroups
where c.AppointDate < "the date of the daygroups for this day").Sum( d =>d)
}
Basically, the query looks in a table for appointments within a certain month and does counts by day for each day of the month. Daygroups groups the results by days so I can do the daily counts. How do I specify the date within the daygroups?
Thanks.
Try
where c.AppointDate < daygroups.Key
Your date is in daygroups.Key
When grouping with LINQ, the value you are grouping on ends up in the Key property of the IGrouping object, daygroups in your case.
Something like this, perhaps:
var test = from a in MyDC.Table
where .....
group a by a.Date into daygroups
select new MyModel {
TheCount = daygroups.Where(d => d.AppointDate < daygroups.Key).Count()
}

Problem with order by in LINQ

I'm passing from the controller an array generated by the next code:
public ActionResult GetClasses(bool ajax, string kingdom)
{
int _kingdom = _taxon.getKingdom(kingdom);
var query = (from c in vwAnimalsTaxon.All()
orderby c.ClaName
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }).Distinct();
return Json(query, JsonRequestBehavior.AllowGet);
}
The query List should be ordered, but it doesn't work, I get the names of the classes ordered wrong in the array, because I've seen it debugging that the names are not ordered.The view is just a dropdownbox loaded automatically, so I'm almost sure the problem is with the action. Do you see anything wrong?Am I missing something?
I think gmcalab is almost there. The reason it's not working is that Distinct blows away the ordering. So you need Distinct THEN OrderBy. But this means you have to sort by the new attribute name:
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrderBy(t => t.taxName);
Give this a try:
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrdeyBy(c => c.ClaName);
In LINQ the Distinct method makes no guarantees about the order of results. In many cases the Distinct causes the OrderBy method to get optimized away. So it's necessary to do the OrderBy last, after the Distinct.
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName })
.Distinct()
.OrderBy(c => c.ClaName);
The select will also blow away the sorting. So either Distinct or Select needs orderby after.

Categories