gpt4 book ai didi

c# - LINQ 按错误结果分组

转载 作者:太空宇宙 更新时间:2023-11-03 14:41:12 26 4
gpt4 key购买 nike

我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com