C# C基于另一个列表字符串对类属性列表进行排序
我使用反射遍历属性列表,并将该值指定给表格单元格。正在循环的类属性被分配到错误的列标题 如何根据标题列表对数据列表属性名称进行排序?他们的名字都一样。我宁愿这样做,也不愿根据属性对标题列表进行排序C# C基于另一个列表字符串对类属性列表进行排序,c#,sorting,reflection,C#,Sorting,Reflection,我使用反射遍历属性列表,并将该值指定给表格单元格。正在循环的类属性被分配到错误的列标题 如何根据标题列表对数据列表属性名称进行排序?他们的名字都一样。我宁愿这样做,也不愿根据属性对标题列表进行排序 public void SetTableStrong<T>(List<T> dataList, List<string> header) { // Define our columns Column c = null; fore
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();
}
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();
}
一种方法是首先将所有属性添加到字典中,然后循环列,并从字典中选择相应的值:
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元素:
您可以缓存属性,然后按照与头相同的顺序获取它们
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);
我想知道您使用的是哪种桌面软件包?@JoeBlow table Pro for Unity3D谢谢!我们曾经建造过自己的…:/