Take()采用与Skip()跳过不同的值

时间:2015-02-26 02:26:40

标签: c# linq

我写了两个不同的查询,第一个应该得到前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,
  • 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

这是我收到的内容

query:VideoGame10,VideoGame9,VideoGame8,VideoGame7,VideoGame5

query2:VideoGame5,VideoGame4,VideoGame3,VideoGame2,VideoGame1

这就是我想要的

query:VideoGame10,VideoGame9,VideoGame8,VideoGame7,VideoGame6

query2:VideoGame5,VideoGame4,VideoGame3,VideoGame2,VideoGame1

我不在乎我是否在第一个查询中获得VideoGame5,只要我同时获得VideoGame5对象和VideoGame6对象。

1 个答案:

答案 0 :(得分:7)

  

与此对象具有相同购买价值的对象永远不会显示

直到我读了几遍这句话才点击。假设您的意思是您拥有以下数据

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, BB, 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);

会解决它。你没有展示你的模型所以我必须编造一个字段Name。在数据库情况下,您通常会有某种主键ID字段,只需按主键排序作为最后一个排序参数,您应该没问题。