gpt4 book ai didi

c# - Linq Complex OrderBy by Props 属性

转载 作者:行者123 更新时间:2023-11-30 17:58:15 25 4
gpt4 key购买 nike

我有一个类,其中一些 Prop 标有一些属性。我想按特定顺序显示它们。到目前为止,我可以对它们进行排序,但不是我想要的顺序。

下面是一个简单的props属性示例

[IncludeInEditor]
[IsInPk]
ID
[IncludeInEditor(IsReadOnlyOnModify=true)]
Name
[IncludeInEditor]
Address
[IncludeInEditor]
DOB


The order that I want is:
1st - Props with IsInPk attribute
2nd - Props with IncludeInEditor(IsReadOnlyOnModify=true)
3rd - Props with IncludeInEditor

到目前为止,我没有成功,也没有 100% 完成(仍然缺少 IsReadOnlyOnModify=true 部分)

var properties =
item.GetType().GetProperties()
.Where(p => p.GetCustomAttributes(true)
.OfType<IncludeInEditorAttribute>()
.Count() > 0)
.Select (x => new
{
Property = x,
Attribute = (IsInPkAttribute)Attribute.GetCustomAttribute(x, typeof(IsInPkAttribute), true)
})
.OrderBy(x => x.Attribute != null ? 1 : -1)
.Select(x => x.Property)
.ToArray();

最佳答案

您可以创建自己的 IComparer<T>比较每个属性的属性的实现:

public class AttributeComparer : IComparer<Attribute>
{
public int Comparer(Attribute x, Attribute y)
{
if(x == null) return y == null ? 0 : -1;
if(y == null) return 1;

if(x is IsInPkAttribute) return (y is IsInPkAttribute) ? 0 : 1;
else if(y is IsInPkAttribute) return -1;
else
{
xa = (IncludeInEditorAttribute)x;
ya = (IncludeInEditorAttribute)y;

if(xa.IsReadOnlyOnModify == ya.IsReadOnlyOnModify) return 0;
else return x.IsReadOnlyOnModify ? 1 : -1;
}
}
}

然后你的查询变成:

var properties = item.GetType().GetProperties()
.Where(p => p.GetCustomAttributes(true)
.OfType<IncludeInEditorAttribute>()
.Any())
.Select (x => new
{
Property = x,
Attribute = Attribute.GetCustomAttribute(x, typeof(IsInPkAttribute), true) ?? Attribute.GetCustomAttribute(x, typeof(IncludeInEditorAttribute, true))
})
.OrderBy(x => x.Attribute, new AttributeComparer())
.Select(x => x.Property)
.ToArray();

关于c# - Linq Complex OrderBy by Props 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12502913/

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