简体   繁体   English

是否存在LINQ查询中的where子句过滤序列的默认顺序

[英]Is there any default order in which where clause in LINQ query filters sequence

public IQueryable<CarVersion> GetCar(int carIdToSearch)
{
    return _Dbcontext.CarVersion.Include("CarFactory").
            .Where(x => x.carId== carIdToSearch);
}

I have CarVersion table, which has two columns version and carId . 我有CarVersion表,它有两列版本和carId Version column is primary key. 版本列是主键。 There can be multiple version for single carId. 单个carId可以有多个版本。 CarFactory table has foreign key version from carVersion table. CarFactory表具有来自carVersion表的外键版本。 So I'm trying to understand, when I execute above query will it always give me results which are ordered in ascending order. 所以我试图理解,当我执行上面的查询时,它总是会给我按升序排序的结果。 Or will it be based on primary key? 或者它将基于主键? Or it can be guaranteed? 还是可以保证? I looked at MS documentation but it does not say anything about ordering. 我查看了MS文档,但没有说明订购。

The result you will get depends on the LINQ-provider. 您将获得的结果取决于LINQ提供程序。 If it's Linq-To-Objects the order is stable(read below). 如果它是Linq-To-Objects,则订单稳定(见下文)。 It means it will be the same as it was in the source sequence. 这意味着它将与源序列中的相同。 If it's a database driven LINQ provider like Linq-To-Entities the order is not predetermined. 如果它是像Linq-To-Entities这样的数据库驱动的LINQ提供程序,则订单不是预先确定的。

You need an ORDER BY in sql to ensure a certain order. 您需要在sql中使用ORDER BY来确保某个订单。 So you need an OrderBy in LINQ: 所以你需要在LINQ中使用OrderBy

return _Dbcontext.CarVersion.Include("CarFactory").
    .Where(x => x.carId== carIdToSearch)
    .OrderBy(x => x.Version);
  • However, even in Linq-To-Objects it's not guaranteed that the order will always be the same. 但是,即使在Linq-To-Objects中,也不能保证订单始终相同。 It also depends on the type of the sequence. 它还取决于序列的类型。 Set based collections like a Dictionary or HashSet also don't guarantee that the order stays the same as you can read here and here . DictionaryHashSet这样的基于集合的集合也不能保证订单与您在此处此处阅读的内容保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM