Sequence包含多个匹配元素

Nov*_*Net 4 c# linq-to-sql

当我试图设置IsDefault每个敷料项目的属性匹配条件时,它会抛出错误说:

序列包含多个匹配序列.

(this.DressingItems
     .Where(xx => xx.DressingInfo.CatID == catId 
                        && xx.ProductID == this.ProductID)
     .Single()).IsDefault = false;
Run Code Online (Sandbox Code Playgroud)

Mat*_*ten 12

好吧,这个例外表明序列DressingItems中至少有两项符合您的Where条件.对Singlethen 的调用会导致异常,因为它断言只传入一个项目.

阅读你的问题让我觉得你想对输入序列的每个项目做一些事情,所以你可能会使用foreach循环:

foreach(var item in this.DressingItems.Where(xx => xx.DressingInfo.CatID == catId && xx.ProductID == this.ProductID))
{
    item.IsDefault = false;
}
Run Code Online (Sandbox Code Playgroud)

  • @NoviceToDotNet这不是LINQ的意图. (3认同)

Dam*_*ith 8

this.DressingItems.Where(x=> x.DressingInfo.CatID == catId && 
                                x.ProductID == this.ProductID).ToList()
                 .ForEach(item=>item.IsDefault = false);
Run Code Online (Sandbox Code Playgroud)

  • 你是对的.在`List`上定义了一个扩展方法,但在我看来这个语句很难阅读并且具有偷渡式拍摄的优雅性=) (2认同)
  • 不 - 也许是资本`E` :)我的个人意见:linq语句提供了一种以紧凑方式查询数据源的好方法,但是`ForEach`扩展方法不对序列进行投影或选择.相反,它将元素传递给它的身体发生的事情并返回无效.它打破了模式:) (2认同)