如果json中存在API编号,我需要将json文件中的文件名和位置替换为新值,否则它应该使用API,File和Location添加新的json数组。我已经编写了foreach循环来执行此操作,但每次将内容添加到列表时,if条件都会采用添加的新api并与列表进行比较,因此它会一次又一次地向json file.Plz添加相同的api,帮助我解决这个问题。
List<DPIndex> items = JsonConvert.DeserializeObject<List<DPIndex>>(json);
foreach (var item in items)
{
foreach (var list in dpIndexList)
{
if (item.API == list.API)
{
item.File = list.File;
item.Location = list.Location;
}
else
{
item.API = list.API;
item.File = list.File;
item.Location = list.Location;
}
}
dpNewIndexList.Add(item);
}
string dpIdxObj = JsonConvert.SerializeObject(dpNewIndexList, Formatting.Indented);
Json文件如下:
[
{
"API": "422833682700000000",
"File": "daf420.dat.07-31-2019",
"Location": 2922
},
{
"API": "422833682700000000",
"File": "daf420.dat.07-31-2019",
"Location": 2922
}
]
发布于 2020-02-04 19:55:49
在看完你的代码之后。看起来你是从同一个对象获取值,然后一次又一次地改变它,看看下面的例子
List<DPIndex> dpIndexList = new List<DPIndex>();
DPIndex index = new DPIndex() {
API = "API.1",
File="API1",
Location="1"
};
dpIndexList.Add(index);
index.API = "API.2";
正如您所看到的,我已经在列表dpIndexList中添加了索引对象,但是在添加它之后,我更改了同一索引对象中的API的值,这也导致了dpIndex列表中的值也发生了更改。你正在对item做同样的事情,你在每次迭代中改变它的状态。所以最后,所有的值都将变成循环的最终迭代,我建议您在每次迭代中创建一个对象,并将其添加到列表中,对于更新,请使用lambda
foreach (var item in items)
{
foreach (var list in dpIndexList)
{
DPIndex it = new DPIndex();
if (item.API == list.API)
{
it.File = list.File;
it.Location = list.Location;
dpNewIndexList.RemoveAll(x=> x.API == list.API);
}
else
{
it.API = list.API;
it.File = list.File;
it.Location = list.Location;
}
dpNewIndexList.Add(it);
}
}
我相信这会对你有帮助
发布于 2020-02-04 21:07:37
下面是一段代码,如果列表中不存在带有"API“的条目,它会将条目添加到dpIndexList
中;如果存在带有"API”的条目,则会更新列表中的条目:
foreach (var item in items)
{
// Check if the item with such API already exists in dpIndexList
var foundItem = dpIndexList.FirstOrDefault(dpItem => dpItem.API == item.API);
if (foundItem != null)
{
// Exists. Update the item in dpIndexList
foundItem.File = item.File;
foundItem.Location = item.Location;
}
else
{
// Doesn't exist. Adding to dpIndexList
dpIndexList.Add(item);
}
}
为了在本地测试的,我使用了以下虚拟列表,并且它起作用了:
var dpIndexList = new List<DPIndex>()
{
new DPIndex
{
API = "1",
File = "File_1_ORIG",
Location = 1111
},
new DPIndex
{
API = "2",
File = "File_2_ORIG",
Location = 2222
},
};
var items = new List<DPIndex>()
{
// Item, which exists in dpIndexList (should update the original)
new DPIndex
{
API = "2",
File = "File_2_UPDATE",
Location = 3333
},
// New item, which doesn't exist in dpIndexList (should be added)
new DPIndex
{
API = "3",
File = "File_3_NEW",
Location = 3333,
},
// Item, which should UPDATE the one above (should update that one)
new DPIndex
{
API = "3",
File = "File_3_UPDATED",
Location = 3333
},
};
附注:不要忘记将using System.Linq;
添加到文件的顶部。
https://stackoverflow.com/questions/60055749
复制相似问题