【问题标题】:LINQ query with group by and ascending ordering not working使用 group by 和升序排序的 LINQ 查询不起作用
【发布时间】:2013-11-01 14:26:46
【问题描述】:

我有一个类成分,它具有 Items 类型的属性 List<Ingredient>
在我的一个页面中,我使用 GridView 来显示所有成分,按首字母分组:

<Page.Resources>
    <CollectionViewSource x:Name="IngredientsViewSource" IsSourceGrouped="True" ItemsPath="Items"/>
</Page.Resources>

页面加载后,CollectionViewSource 的 Source 属性设置如下:

this.IngredientsViewSource.Source = CurrentData.Ingredients.GroupedItems;

GroupedItems 是 Ingredients 类的一个属性,它采用属性 Items 并对所有内容进行排序和分组,以便可以使用:

public object GroupedItems
{
    get
    {
        if (this.Items != null)
        {
            return from IngredientIteration in this.Items
                       //orderby IngredientIteration.Name ascending
                       group IngredientIteration 
                           by IngredientIteration.FirstLetter
                           into IngredientGroup
                           //orderby IngredientGroup.Key ascending
                           select new { 
                                        FirstLetter = IngredientGroup.Key, 
                                        Items = IngredientGroup 
                                      };
        }
        else 
        {
            return null;
        }
    }
    private set { }
}

这工作得很好。现在我想对结果进行排序,因为现在第一个字母的顺序都搞砸了。但是,当我删除两个 orderby 子句前面的注释标记时,它变得非常奇怪。现在保留 orderby 子句会导致正确排序的组,但只显示每个组的第一项。
但是,当我将升序更改为降序时,一切都按预期进行:组按降序排序,显示所有项目,并且每个组内的项目按降序排序。

这对我来说毫无意义,为什么下降有效但上升无效?我在这里遗漏了什么吗?

【问题讨论】:

  • 在我看来,您的GroupedItems 会将Items 作为IGrouping&lt;...&gt;,我怀疑这不是您想要的。 GroupedItems 中每个条目的实际数据结构是什么?
  • 我想要这些匿名对象的集合,每个对象都有一个字符串 FirstLetter 和一个 List&lt;Ingredient&gt; Items

标签: c# linq sorting windows-runtime winrt-xaml


【解决方案1】:

虽然正如您所描述的(下降有效,但上升无效),这太奇怪了。您的查询没有什么复杂的,我会使用 method syntax 它应该可以按您的预期工作:

public object GroupedItems {
  get {
    if (this.Items != null)
    {
        return Items.OrderBy(item=>item.Name)
                    .GroupBy(item=>item.FirstLetter)
                    .OrderBy(g=>g.Key)
                    .Select(g=> new {
                               FirstLetter = g.Key,
                               Items = g.ToList()
                            }).ToList();
    }
    else  {
        return null;
    }
  }
  private set { }
}

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 2017-09-09
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多