我有工作日列表
绑定到DataGrid
:
ItemsSource="{Binding Path=MyConceptItems}"
然后我从json其他列表中获取并尝试使用日期进行匹配:
public ObservableCollection<MyDataConcept> MyConceptItems { get; set; }
public void GetSheet(string fd, string ld){
string period = "\"" + fd + "\",\"" + ld + "\"";
string result = Task.Run(() => MyMethodAsync("getsheet", GetApiKeyAsync(), "," + period)).
GetAwaiter().GetResult();
MyObject resultparsed = new JavaScriptSerializer().Deserialize<MyObject>(result);
foreach (var item in resultparsed.result.items) {
foreach (var existingItem in MyConceptItems) {
if (existingItem.DateColumn == item.entryDate) {
existingItem.PColumn = item.pName;
existingItem.TColumn = item.aName;
existingItem.HSpend = item.formattedDuration;
}}}};
我的问题是:当我从json中获得两个具有相同日期的结果时,则仅显示一个(最后一个)项目,可能会被覆盖。
示例:
MyConecptItems
:
Date | PColumn
2018-09-03 | A2
2018-09-04 | B
2018-09-05 | C2
来自Json
:
Date | PName
2018-09-03 | A
2018-09-03 | A2
2018-09-04 | B
2018-09-05 | C
2018-09-05 | C2
更新:
我正在尝试执行以下操作:
foreach (var item in resultparsed.result.items) {
foreach (var existingItem in MyConceptItems) {
if (existingItem.DateColumn == item.entryDate)
if (existingItem.IsExist == false){
existingItem.IsExist = true;
existingItem.ProjectColumn = item.projectName;
existingItem.TaskColumn = item.activityName;
existingItem.HoursSpend = item.formattedDuration;
}
else
{
MyConceptItems.Add(new MyDataConcept(item.entryDate, item.entryDayName,
item.projectName, item.activityName, item.formattedDuration);
}
}}
但是有以下消息:
System.InvalidOperationException:
'Collection was modified; enumeration operation may not execute.'
答案 0 :(得分:1)
使用foreach
循环枚举集合时,您无法对其进行修改。尝试这样的事情:
foreach (var item in resultparsed.result.items)
{
var existingItem = MyConceptItems.FirstOrDefault(x => x.DateColumn == item.entryDate);
if(existingItem != null)
{
//update properties...
}
else
{
//add new item
MyConceptItems.Add(new MyDataConcept(item.entryDate, item.entryDayName,
item.projectName, item.activityName, item.formattedDuration);
}
}
答案 1 :(得分:0)