首页 > 解决方案 > 设置列表中的值不工作

问题描述

我为我的大问题写了一个片段,我在读取和格式化后在同一个对象中设置一个值。虽然值是从对象位置读取的,但它没有设置它。

我正在根据索引和属性访问对象。

class Student
{
    public string City { get; set; }
    public double value1 { get; set; }
    public double value2 { get; set; }
}

上面是用于初始化列表的 POCO。以下是存在问题的代码

class ClassTest
{
    public static List<dynamic> GetUpdatedListCurrency(string[] CurrecyColumns, List<dynamic> dynamicList)
    {
        int Count = CurrecyColumns.Count();

        string first = CurrecyColumns.First();
        string two = CurrecyColumns.Skip(1).First();

        for (int i = 0; i < dynamicList.Count; i++)
        {
            var t = ((double)(dynamicList[i][first])).ToString("N", CultureInfo.CreateSpecificCulture("en-US"));
            var tt = ((double)(dynamicList[i][two])).ToString("N", CultureInfo.CreateSpecificCulture("en-US"));

            //Formatted value is availble at t and tt but it is not set back to that object

            dynamicList[i][first] = t;
            dynamicList[i][two] = tt;
        }

        return dynamicList;
    }

    static void Main()
    {
        var list = new List<Student>()
        {
            new Student() { City="Noida", value1 = 44412, value2 = 33341 },
            new Student() { City="Delhi", value1 = 11212, value2 = 3421 }
        };

        var converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
        dynamic expandoObjectList = JsonConvert.DeserializeObject<List<ExpandoObject>>(JsonConvert.SerializeObject(list), converter);

        string Columns = " value1 as value3, value2 as value4";

        var res = ((List<ExpandoObject>)expandoObjectList)
                       .ToDynamicList().AsQueryable()
                       .Select("new (" + Columns + ")")
                       .ToDynamicList().ToList();

        string str = "value3,value4";
        var updatedList = GetUpdatedListCurrency(str.Split(','), res);

    }
}

标签: c#dynamiccore

解决方案


好的。所以最后我用其他解决方案完成了它,但我仍然不清楚为什么上面不应该设置这个值。欢迎有深度的朋友详细解答。下面是我的工作代码。我用索引访问了动态列表并设置了值。

for (int i = 0; i < dynamicList.Count; i++)
                    {
                        dynamicList[i].GetType().GetProperty(first)
                            .SetValue(dynamicList[i], ((double)(dynamicList[i][first])).ToString("N", CultureInfo.CreateSpecificCulture("fr")), null);

                        dynamicList[i].GetType().GetProperty(two)
                            .SetValue(dynamicList[i], ((double)(dynamicList[i][first])).ToString("N", CultureInfo.CreateSpecificCulture("fr")), null);
                    }

推荐阅读