gpt4 book ai didi

c# - 使用 Linq 更新集合中除一个对象之外的所有对象

转载 作者:太空狗 更新时间:2023-10-29 22:07:22 25 4
gpt4 key购买 nike

有没有办法使用 Linq 执行以下操作:

foreach (var c in collection)
{
if (c.Condition == condition)
{
c.PropertyToSet = value;
// I must also check I only set this value to one minimum and only one element.
}
else
{
c.PropertyToSet = otherValue;
}
}

澄清一下,我想遍历集合中的每个对象,然后更新每个对象的属性,但集合中的一个元素应该更新为另一个值。

此时我使用一个计数器来检查我将我的值设置为我的集合中的一个且只有一个元素。我从这个例子中删除了它,让人们提出其他解决方案。

收藏中无一异常(exception)的原题都是here

编辑

我问这个问题是因为我不确定是否可以使用 LinQ 做到这一点。所以你的回答安慰了我对 LinQ 的看法。谢谢。

最佳答案

您可以使用 .ForEach 进行更改,并使用 .Single 验证只有一个元素符合条件:

// make sure only one item matches the condition
var singleOne = collection.Single(c => c.Condition == condition);
singleOne.PropertyToSet = value;

// update the rest of the items
var theRest = collection.Where(c => c.Condition != condition);
theRest.ToList().ForEach(c => c.PropertyToSet = otherValue);

关于c# - 使用 Linq 更新集合中除一个对象之外的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15389505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com