我的 table
userid UserApproveLevel_Two_T
1118bda4-6cba-43d6-a0cd-555555555555 True
22299872-aa01-498a-831d-555555555555 False
333a8ddb-d261-47d9-8ec8-555555555555 False
-
var sky = DB.UserSkypeTrackers.GroupBy(x => x.UserApproveLevel_Two_T == true).FirstOrDefault();
-
foreach (var item in sky )
{
// in here i see
//22299872-aa01-498a-831d-555555555555
//333a8ddb-d261-47d9-8ec8-555555555555
}
-
我应该看到
1118bda4-6cba-43d6-a0cd-555555555555
在我的 foreach 中
为什么我看到错误的结果??
谢谢
最佳答案
Enumerable.GroupBy
根据文档,LINQ to Objects 中的方法保留分组的顺序:
The
IGrouping<TKey,TElement>
objects are yielded in an order based on the order of the elements insource
that produced the first key of eachIGrouping<TKey,TElement>
. Elements in a grouping are yielded in the order they appear insource
.
这可能是您期望看到的 111...
.
但是,您似乎正在使用 GroupBy
在数据库表或类似的东西上。这意味着您正在使用 Queryable.GroupBy
.根据它的文档,
The query behavior that occurs as a result of executing an expression tree that represents calling
GroupBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>)
depends on the implementation of the type of the source parameter. The expected behavior is that it groups the elements of source by a key value that is obtained by invoking keySelector on each element.
如您所见,确切的行为是特定于实现的,它不必保留顺序。因此,第一个 IGrouping
不一定是带键 true
的组.
因此,为了获得您想要的结果,您可以:
- 使用
Where
使用键true
找到组, 或 - 首先将所有对象加载到内存中,然后使用 LINQ to Object 的
GroupBy
. (如果数据库中有很多对象,这可能会很慢)
关于c# - LINQ 按错误结果分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815924/