2016-02-23 142 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); 
相关问题