c# - LINQ 按错误结果分组

标签 c# sql linq

我的 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 in source that produced the first key of each IGrouping<TKey,TElement>. Elements in a grouping are yielded in the order they appear in source.

这可能是您期望看到的 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/

相关文章:

c# - 使用 ToDictionary 创建字典

mysql - 基于mySql中列值的一部分分组

linq - 使用 linq 匹配多个字段时优先考虑字段

c# - 滚动时图像是如何下载的?

c# - Kinect 深度和图像帧对齐

MySQL对3张表进行连接查询

sql - 在 PostgreSQL 中插入空值会导致错误

c# - Linq GROUP BY 和 SUM 可为空长

.net - Entity Framework - 已添加具有相同键的项目。 - 尝试定义外键关系时出错

c# - 使用 iText 7 for .NET 时如何定义 Colspan 和 Rowspan