Linq query to get person visited zones of current day

家住魔仙堡 提交于 2019-12-12 03:46:48

问题


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.


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/43181190/linq-query-to-get-person-visited-zones-of-current-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!