程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> c# 根據自定義Attribute排序

c# 根據自定義Attribute排序

編輯:C#基礎知識
add a class: 

public class ExportAttribute : Attribute {     public int FieldOrder { get; set; }     public ExportAttribute() { } }


add [ExportAttribute(FieldOrder = 2)] on the Field
 [DisplayName("Department Name")]
 [ExportAttribute(FieldOrder = 2)]
 public string DepartmentName {
     get {
         return this.Department.DepartmentName;
     }
 }



Get the class's filed those have the DisplayName Attribute and order by the FieldOrder DisplayName
public PropertyInfo[] GetPropertyInfoArray(Type type)
       {
           PropertyInfo[] props = null;
           try
           {
               object obj = Activator.CreateInstance(type);
               //props = (from r in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
               //         where r.GetCustomAttribute(typeof(DisplayNameAttribute)) != null
               //         select r).ToArray();
 
               props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                       .Select(x => new 
                       { 
                           Property = x, 
                           Attribute = (ExportAttribute)Attribute.GetCustomAttribute(x, typeof(ExportAttribute), true) 
                       })
                       .Where(x => x.Property.GetCustomAttribute(typeof(DisplayNameAttribute)) != null )
                       .OrderBy(x => x.Attribute != null ? x.Attribute.FieldOrder : -1)
                       .Select(x => x.Property )
                       .ToArray();
           }
           catch (Exception ex)
           {
               AppLogger.LogErrorOnly(ex);
           }
           return props;
 
       }










  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved