Lambda 表达式 - 根据对象集合中另一个属性的值设置对象集合中另一个属性的值
我是 lambda 表达式的新手,希望利用语法根据集合中的另一个值设置集合中一个属性的值
通常我会执行一个循环:
class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
void Run()
{
Item item1 = new Item { Name = "name1" };
Item item2 = new Item { Name = "name2" };
Item item3 = new Item { Name = "name3" };
Collection<Item> items = new Collection<Item>() { item1, item2, item3 };
// This is what I want to simplify.
for (int i = 0; i < items.Count; i++)
{
if (items[i].Name == "name2")
{
// Set the value.
items[i].Value = "value2";
}
}
}
I'm new to lambda expressions and looking to leverage the syntax to set the value of one property in a collection based on another value in a collection
Typically I would do a loop:
class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
void Run()
{
Item item1 = new Item { Name = "name1" };
Item item2 = new Item { Name = "name2" };
Item item3 = new Item { Name = "name3" };
Collection<Item> items = new Collection<Item>() { item1, item2, item3 };
// This is what I want to simplify.
for (int i = 0; i < items.Count; i++)
{
if (items[i].Name == "name2")
{
// Set the value.
items[i].Value = "value2";
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LINQ 通常对于选择数据比修改数据更有用。但是,您可以编写如下内容:
首先选择需要修改的项目,然后使用标准命令式循环修改所有项目。您可以将
foreach
循环替换为可用于列表的ForAll
方法,但我认为这不会给您带来任何优势:请注意,您需要添加
ToList
在中间,因为ForEach
是一项 .NET 2.0 功能,仅适用于List
类型 - 不适用于所有IEnumerable类型。
类型(与其他 LINQ 方法一样)。如果您喜欢这种方法,您可以为IEnuerable
实现ForEach
:无论如何,我更喜欢
foreach
循环,因为这也使得很明显,您正在做一些修改 - 在代码中轻松看到这一事实很有用。LINQ is generally more useful for selecting data than for modifying data. However, you could write something like this:
This first selects items that need to be modified and then modifies all of them using a standard imperative loop. You can replace the
foreach
loop withForAll
method that's available for lists, but I don't think this gives you any advantage:Note that you need to add
ToList
in the middle, becauseForEach
is a .NET 2.0 feature that's available only forList<T>
type - not for allIEnumerable<T>
types (as other LINQ methods). If you like this approach, you can implementForEach
forIEnuerable<T>
:Anyway, I'd prefer
foreach
loop, because that also makes it clear that you're doing some mutation - and it is useful to see this fact easily in the code.