【问题标题】:LINQ GroupBy and then OrderBy a property from the previous queryLINQ GroupBy 然后 OrderBy 来自上一个查询的属性
【发布时间】:2014-06-05 09:59:17
【问题描述】:

所以我有一个CategoryAttribute 类:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method, AllowMultiple = false)]
public class CategoryAttribute : PropertyAttribute
{
    public readonly string name;
    public readonly float order;

    public CategoryAttribute(string name, float order)
    {
        this.name = name;
        this.order = order;
    }
}

这样我就可以对班级成员进行分类以分组绘制检查器 (Unity3D),如下所示:

现在这些是默认组(“字段”的顺序为 0,“属性”的顺序为 1,“方法”的顺序为 2)。

现在我想让用户用自己的名字和顺序创建自己的类别,所以说我想创建一个“调试”类别:

[Category("Debug", 3)]
public bool debugMode;
[Category("Debug", 3)]
public bool drawGizmos;
[Category("Debug", 3)]
public Color gizmosColor;

现在这三个字段都将在“方法”之后的一个名为“调试”的类别中绘制(因为它具有更高的顺序)(我知道语法是重复的,我稍后会做一些事情......)

现在我似乎无法按类别名称对我的成员进行分组,并按该类别订单号对这些组进行排序,我尝试过但遇到了问题:

var members = fields.Concat<MemberInfo>(properties).Concat(methods);

var userCategories = from m in members
                     let cat = m.GetCustomAttributes(typeof(CategoryAttribute), false)[0]
                     where attr != null
                     let cat = attr as CategoryAttribute
                     group m by cat.name into g
                     orderby cat.order // bump!

还有:

var userCategories = members.Select(m => new {m, cat = m.GetCustomAttributes(typeof(CategoryAttribute), false)[0] as CategoryAttribute})
                            .Where(x => x.cat != null)
                            .GroupBy(x => x.cat.name)
                            .OrderBy(x => x.cat.order) // duh!

现在我可以摆弄预测并最终弄清楚,但这可能不是最好的,所以我想也许有人可以帮助我以正确的方式做到这一点。

再次,我想按类别名称对我的成员进行分组,并按类别编号对组进行排序。

谢谢!

【问题讨论】:

  • 如果您有两个名称相同但顺序不同的类别,您希望发生什么? (这与 SQL 有什么关系?看起来这将通过 LINQ to Objects 完成......)
  • 好吧,我可能会向我的用户添加注释,以免这样做。但以防万一,我可能会将这两个组中的成员合并为一个组,并以两个重复组中较小的顺序绘制该组。
  • 哦,你的意思是我添加了错误的标签?抱歉,我认为那是针对 linq 的 sql'ish 非点句语法...我将其删除。

标签: c# linq group-by


【解决方案1】:

如果这是在 LINQ to Objects 中,您可以使用:

.OrderBy(g => x.First().cat.order)

或者,您可以按名称​​和顺序分组,然后使用键的顺序部分:

.GroupBy(x => new { x.cat.name, x.cat.order })
.OrderBy(g => g.Key.order)

基本上,您需要了解在GroupBy 之后您没有可以要求类别的单个项目 - 您有一组项目。因此,您需要询问与另一个 相比,您将如何订购 该组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多