避免覆盖 ObservableCollection 中的值(C#、WPF)

Avoid to overwrite values inside ObservableCollection (C#, WPF)

我有工作日列表

绑定到 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 两个具有相同日期的结果 然后进入 MyConceptItems 时只显示一个(最后一个)项目,可能被覆盖。

示例:

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.'

您不能在使用 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);
    }
}

您正在使用行

迭代 ObservableCollection
foreach (var existingItem in MyConceptItems) {

以这种方式循环使用集合的迭代器。然后您将在该循环内添加一个项目:

MyConceptItems.Add(new MyDataConcept(...

在修改集合本身时不能使用集合枚举器(可以修改集合中某项的属性)。

考虑更改您的代码以使用这些方便的工具之一 IList extension methods which allow you to specify a predicate (a condition to select a specific object): Contains, Any, Select or SingleOrDefault。如果这些方法没有 return 您期望的项目,那么您可以向集合中添加一个新项目。