按 ConcurrentDictionary 中的任何 Value.Field 排序

问题描述 投票:0回答:1

我正在尝试使用 ConcurrentDictionary(如 List())加载 GridView 并允许任何字段(key 或 object.field)可排序。也就是说:

public static ConcurrentDictionary<string, Detail> myDic = new ConcurrentDictionary<string, Detail>();

public class Detail
{
    public int val1;
    public bool val2;
    public DateTime val3;
    public long val4;
}

// myDic is loaded elsewhere and does have correct data

private void LoadGridView(string sortBy = "Key")
{
    Type valType = typeof(Detail);
    PropertyInfo pInfo;

    // method #1:
    pInfo = valType.GetProperty(sortBy);        // <-- always returns null

    // method #2:
    FieldInfo fInfo = valType.GetField(sortBy);             // <-- always returns correct field info
    pInfo = fInfo.ReflectedType.GetProperty(fInfo.Name);    // <-- always returns null

    // fails when sortBy != "Key"
    GridView1.DataSource = myDic.OrderBy(x => sortBy == "Key" 
        ? x.Key 
        : pInfo.GetValue(x.Value)
    ).ToList();

    GridView1.DataBind();
}

显然,我在测试时要么使用方法#1,要么使用方法#2——而不是同时使用两种方法! ;)

当我指定 sortBy = 详细信息字段(“val1”、“val2”等 - 拼写、大小写验证)时,pInfo 始终为 null 并且对数据源的分配失败。

预先感谢您的帮助!

.net linq dictionary concurrentdictionary getproperty
1个回答
0
投票

您没有提供任何数据。所以我必须创建自己的...... 将参数更改为 Key、val1 或 val4 以查看 orderby

void Main()
{
    Enumerable.Range(1, 100).ToList().AsParallel().ForAll(fe=> {
        myDic.AddOrUpdate("A"+fe, new Detail() { val1 = fe, val2 = true, val3 = DateTime.Now, val4 = GetLong() }, (_, old) => old); 
    });
        
    string sortBy = "val4";
    LoadGridView(sortBy);
}

public long GetLong()
{
    var r = new Random();
    return r.Next(0, 1000) * 2;
}

private void LoadGridView(string sortBy)
{
        myDic
        .OrderBy(p => sortBy != "Key" ? p.Value.GetType().GetField(sortBy).GetValue(p.Value) : p.Key) 
        .ToList()
        .Dump();
}

public ConcurrentDictionary<string, Detail> myDic = new  ConcurrentDictionary<string, Detail>();

public class Detail
{
    public int val1;
    public bool val2;
    public DateTime val3;
    public long val4;
    public Detail(){}
}
© www.soinside.com 2019 - 2024. All rights reserved.