如何对ConcurrentDictionary的任意字段(Key或对象字段)排序并绑定GridView
问题原因与解决方法
你的核心问题是混淆了C#中的字段(Field)和属性(Property):
Detail类里的val1、val2等都是公共字段(语法为public int val1;)Type.GetProperty()方法专门用于获取属性(语法为public int Val1 { get; set; }这种带访问器的成员),所以无论怎么调用都无法得到有效结果。
方案1:将字段改为属性(推荐)
这是.NET数据类的标准写法,更适配数据绑定和反射场景:
public class Detail { public int Val1 { get; set; } public bool Val2 { get; set; } public DateTime Val3 { get; set; } public long Val4 { get; set; } }
修改后,原代码里的Type.GetProperty(sortBy)就能正常获取PropertyInfo,排序逻辑可直接复用。
方案2:直接使用字段反射(不修改Detail类)
如果不想改动Detail类,可直接用FieldInfo获取字段值,调整排序逻辑:
private void LoadGridView(string sortBy = "Key") { Type valType = typeof(Detail); FieldInfo fInfo = valType.GetField(sortBy); GridView1.DataSource = myDic.OrderBy(x => sortBy == "Key" ? x.Key : fInfo.GetValue(x.Value) ).ToList(); GridView1.DataBind(); }
内容的提问来源于stack exchange,提问作者dwneder
相关产品推荐
相关产品推荐

