如何在不创建新对象的情况下指定doddlereport的列顺序
本文关键字:情况下 doddlereport 顺序 对象 创建 新对象 | 更新日期: 2023-09-27 18:10:58
我试图利用CustomAttributes来指定对象的属性顺序
public class WCG : DistrictExport
{
[DataMember(Name = "Survey", Order = 190)]
public string Survey { get; set; }
[DataMember(Name = "Western Hemisphere'nwith Europe", Order = 200)]
public string WesternHemisphereWithEurope { get; set; }
[DataMember(Name = "Eastern Hemisphere", Order = 210)]
public string EasternHemisphere { get; set; }
}
如何在不创建新对象的情况下指定doddlereport的列顺序?
List<object> report = GetReportResults();
report = new Report(results.ToReportSource(), Writer);
OK!,我试试你的问题。我工作得很好。试试我的来源:
我的简单测试类:
public class Test
{
[DataMember(Name = "A", Order = 96)]
public string A { get; set; }
[DataMember(Name = "B", Order = 97)]
public string B { get; set; }
[DataMember(Name = "C", Order = 98)]
public string C { get; set; }
}
Ext: 和
public static class Ext
{
public static IList<KeyValuePair<string, int>> AsOrderColumns<T>(this T t)
where T : class
{
return t.GetType()
.GetProperties()
.Where(w => w.IsOrderColumn())
.Select(s => s.GetOrderColumn())
.OrderBy(o => o.Value)
.ToList();
}
private static bool IsOrderColumn(this PropertyInfo prop)
{
return prop.GetCustomAttributes(typeof(DataMemberAttribute), true)
.Any();
}
private static KeyValuePair<string, int> GetOrderColumn(this PropertyInfo prop)
{
var attr = prop.GetCustomAttributes(typeof(DataMemberAttribute), true)
.ElementAt(0) as DataMemberAttribute;
return (attr != null)
? new KeyValuePair<string, int>(attr.Name, attr.Order)
: new KeyValuePair<string, int>();
}
public static IList<object> AsOrderRow<T>(this T t)
where T : class
{
return t.GetType()
.GetProperties()
.Where(w => w.IsOrderColumn())
.OrderBy(o => o.GetOrderColumn().Value)
.Select(s => s.GetValue(t, null))
.ToList();
}
}
控制台测试代码:
class Program
{
static void Main(string[] args)
{
var test = new Test();
var tests = new List<Test>()
{
new Test() {A = "A-1.1", B = "B-1.2", C = "C-1.3"},
new Test() {A = "A-2.1", B = "B-2.2", C = "C-2.3"},
new Test() {A = "A-3.1", B = "B-3.2", C = "C-3.3"},
new Test() {A = "A-4.1", B = "B-4.2", C = "C-4.3"}
};
Console.WriteLine(String.Join<string>("'t", test.AsOrderColumns().Select(s => String.Format("{0}({1})", s.Key, s.Value))));
foreach (var item in tests)
{
Console.WriteLine(String.Join<object>("'t", item.AsOrderRow()));
}
Console.ReadKey();
}
}