【问题标题】:How to merge the output from foreach loop into one?如何将foreach循环的输出合并为一个?
【发布时间】:2019-04-09 06:42:36
【问题描述】:

Code 类似于主项,而 IdSub 类似于主项的子项。 1 个主项可能有多个子项。

我的代码后面有这个 foreach 代码。

 foreach (var subID in Ids)
     {
          Display display = new Display();

           display.Code = item.Code;
           display.Name = item.Name;
           display.Price = item.Price;
           display.IdSub = subID ;
           DisplayList.Add(display);
    }

由于 Ids 有 3 个 subID,所以输出有 3 行数据。我想要的是因为 CodeNamePrice 与主要项目相同。我希望它与多个 IdSub 合并为 1 行。如何合并/合并这些数据?

【问题讨论】:

标签: c# .net wpf foreach binding


【解决方案1】:

然后,您需要将 Display 类上的 IdSub 字段/属性更改为整数数组:int[](您可以采用不同的方式,但这是 IMO 的最佳方法)。

那么你可以省略循环:

Display display = new Display()
{
  Code = item.Code,
  Name = item.Name,
  Price = item.Price,
  IdSub = Ids //if Ids is array of ints, else you need to use ToArray() method
}

DisplayList.Add(display);

要通过绑定显示IdSub 的数据,您需要在Display 类上定义附加属性:

public string IdSubDisplay
{
  get
  {
    return string.Join(",", IdSub);
  }
  set { }
}

并绑定到IdSubDisplay

【讨论】:

  • 它给Ids 一个错误,因为Ids 是这样的列表List<int> Ids =...
  • @newbie 然后将IdSub定义为List<int>或者写成IdSub = Ids.ToArray()
  • 先生,我已经尝试了您的方法,现在没有错误,但是我的 Id Sub 输出变成了这样 Int32[] Array 哪里出错了?它没有显示 id sub
  • @newbie 你是怎么显示的?您应该使用string.Join 方法来显示集合中的所有元素:string.Join(",", display.IdSub);
  • 我像这样使用Binding <ListBoxItem Content="{Binding IdSub}"/> 我应该把字符串放在哪里。加入?
【解决方案2】:

您有多种选择。这是最简单的一种:

foreach (var id in itemIds)
{
    if (DisplayList.Any(x=> x.Code == item.Code && x.Name == item.Name && x.Price == item.Price))
    {
        var display = DisplayList.Single(x=> x.Code == item.Code && x.Name == item.Name && x.Price == item.Price);
        display.IdSubs.Add(id);//change IdSub to IdSub, as a list of its previous type
    }
    else
    {
        Display display = new Display();
        display.Code = item.Code;
        display.Name = item.Name;
        display.Price = item.Price;
        display.IdSubs = new List<int>();//Assumed that IdSub was int
        DisplayList.Add(display);
    }
}

【讨论】:

  • 我在使用这种方法时遇到了一些错误。因为在我的itemIds 里面只包含id 它不包含除此之外的任何其他内容。
  • itemIds 看起来像这样 `List itemIds =...`
  • 我在 if 语句中进行了编辑,请检查一下。
  • 我这里有错误new List&lt;int&gt;();它说Cannot implicitly convert type 'System.Collections.Generic.List&lt;int&gt;' to 'int'
  • 这里是display.IdSubs.Add(id);,上面写着'int' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多