c# - 设置列表中的值不工作
问题描述
我为我的大问题写了一个片段,我在读取和格式化后在同一个对象中设置一个值。虽然值是从对象位置读取的,但它没有设置它。
我正在根据索引和属性访问对象。
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);
}
}
解决方案
好的。所以最后我用其他解决方案完成了它,但我仍然不清楚为什么上面不应该设置这个值。欢迎有深度的朋友详细解答。下面是我的工作代码。我用索引访问了动态列表并设置了值。
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);
}
推荐阅读
- python - 正则表达式忽略数字后跟一个单词/非数字字符
- javascript - 如何避免 ClickesitemsType 数组数字出现在 javascript 中的 SelectedclassNamesFirstLevel 数组中
- spring - Wildfly 服务器在部署后自动关闭
- r - ggbiplot 以前与 prcomp 一起工作,现在不会
- angular - 有哪些方法可以改善 Angular 中的渲染?
- bash - Youtube 脚本已停止处理搜索顺序
- javascript - array.splice 具有负值索引的意外行为
- ruby-on-rails - 我可以在浏览器收到之前修改 Capybara 页面正文吗?
- machine-learning - 如何确定是否对给定场景使用机器学习算法或数据挖掘技术?
- c# - 获取数字的子字符串