c# – Take()采用与Skip()跳过不同的值
我写了两个不同的查询,第一个应该得到前5个对象,然后下一个应该得到按购买值排序的下5个对象.问题是中间的两个值是相同的,当我取前五个对象,然后跳过前五个对象并取下一个五个对象时,第一个集合的最后一个对象与第一个对象的第一个值相同从不显示第二组和与此对象具有相同购买价值的对象.我的疑问如下.
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); 我想知道是否有一些我可以采取不同的方式来防止这种情况发生. 编辑:我觉得我的解释可能有点令人困惑,所以我要在数据库中添加一个给出10个VideoGame对象的例子并购买了价值. > VideoGame1.purchased = 1, 这是我收到的 查询:VideoGame10,VideoGame9,VideoGame8,VideoGame7,VideoGame5 query2:VideoGame5,VideoGame4,VideoGame3,VideoGame2,VideoGame1 这就是我想要的 查询:VideoGame10,VideoGame6 query2:VideoGame5,VideoGame1 我不在乎我是否在第一个查询中获得VideoGame5,只要我同时获得VideoGame5对象和VideoGame6对象. 解决方法
直到我读了几遍这句话才点击.假设您的意思是您拥有以下数据 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); } 你得到的结果有A,B和B,D …… 问题是你没有确定性排序,当有一个平局时,它取决于执行orderby的任何底层系统(可能是SQL服务器,这是EF或类似). 要解决这个问题,你必须使你的分拣系统更加具体,这样排序引擎就没有任何模糊的联系来决定你. 将你的队员改为 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); 会解决它.你没有展示你的模型所以我不得不编造一个字段名称.在数据库情况下,您通常会有某种主键ID字段,只需按主键排序作为最后一个排序参数,您应该没问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |