2016-02-23 140 views
2

我使用反射遍歷屬性列表,併爲該表格單元賦值。我正在循環的類屬性被分配到錯誤的列(標題)。C#根據另一個列表字符串對類屬性進行排序

如何根據標題列表對dataList屬性名稱進行排序?他們都被命名爲相同。我寧願這樣做比根據屬性對頭部列表進行排序。

dataList類型將始終是一個具有屬性的類。

public void SetTableStrong<T>(List<T> dataList, List<string> header) 
{  
    // Define our columns 
    Column c = null; 
    foreach (var item in header) 
    { 
     c = table.addTextColumn(item); 
     c.horAlignment = Column.HorAlignment.CENTER; 
    } 

    // Initialize Your Table 
    table.initialize(); 
    table.data.Clear(); 

    foreach (var item in dataList.Select((value, index) => new { value, index })) 
    { 
     Datum d = Datum.Body(item.index.ToString()); 

     //Property set to wrong header because they are not sorted to the same as headers. 
     foreach (var property in item.value.GetType().GetProperties()) 
     { 
      var value = property.GetValue(item.value, null); 

      if (value == null) 
       continue; 

      d.elements.Add(value.ToString()); 
     } 
     table.data.Add(d); 
    } 

    // Draw Your Table 
    table.startRenderEngine(); 
} 
+0

我在想你正在使用哪個'table'包? – Fattie

+0

@JoeBlow https://www.assetstore.unity3d.com/en/#!/content/42831 Unity3D的表格專業版 –

+0

謝謝!我們建立了自己的一次......:/ – Fattie

回答

2

一種方法是將所有屬性從字典添加到Dictionary<string,string>,然後再環列,並選擇相應的值:

var propValueByName = item 
    .value 
    .GetType() 
    .GetProperties() 
    .Select(p => new { 
     p.Name 
    , Val = p.GetValue(item.value, null) 
    }).Where(p => p.Val != null) 
    .ToDictionary(p => p.Name, p => p.Val.ToString()); 

現在環列,並添加propValueByName[columnName]d.elements

foreach (var columnName : header) { 
    d.elements.Add(propValueByName[columnName]); 
} 
table.data.Add(d); 
0

你可以緩存你的屬性,然後以相同的順序比你的頭獲取它們。

private static Dictionary<Type, PropertyInfo[]> TypeProperties 
    = new Dictionary<Type, PropertyInfo[]>(); 
public IEnumerable<PropertyInfo> GetTypeProperties<T>() 
{ 
    Type type = typeof(T); 
    PropertyInfo[] properties; 
    if (!TypeProperties.TryGetValue(type, out properties)) 
     TypeProperties.Add(type, properties = type.GetProperties()); 
    return properties; 
} 

/* Fixed excerpt from your code */ 

var properties = GetTypeProperties<T>(); 
foreach (var hdr in header) 
{ 
    var property = properties.FirstOrDefault(p => p.PropertyName == hdr); 
    if (property != null) 
    { 
     var value = property.GetValue(item.value, null); 
     if (value==null) //Doesn't this also mess the order? 
      continue; 
     d.elements.Add(value.ToString()); 
    } 
} 
table.data.Add(d); 
相關問題