我们如何在C#中使用LINQ更新集合的值?
如果集合是List,则可以使用LINQ中可用的ForEach扩展方法。
示例
using System;
using System.Collections.Generic;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
List<Fruit> fruits = new List<Fruit> {
new Fruit {
Name = "Apple",
Size = "Small"
},
new Fruit {
Name = "Orange",
Size = "Small"
}
};
foreach(var fruit in fruits) {
Console.WriteLine($"Fruit Details Before Update. {fruit.Name}, {fruit.Size}");
}
fruits.ForEach(fruit => { fruit.Size = "Large"; });
foreach (var fruit in fruits) {
Console.WriteLine($"Fruit Details After Update. {fruit.Name}, {fruit.Size}");
}
Console.ReadLine();
}
}
public class Fruit {
public string Name { get; set; }
public string Size { get; set; }
}
}输出结果
上面代码的输出是
Fruit Details Before Update. Apple, Small Fruit Details Before Update. Orange, Small Fruit Details After Update. Apple, Large Fruit Details After Update. Orange, Large
如果要基于条件更新列表项,则可以使用Where()子句。
示例
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
IEnumerable<Fruit> fruits = new List<Fruit> {
new Fruit {
Name = "Apple",
Size = "Small"
},
new Fruit {
Name = "Orange",
Size = "Small"
},
new Fruit {
Name = "Mango",
Size = "Medium"
}
};
foreach(var fruit in fruits) {
Console.WriteLine($"Fruit Details Before Update. {fruit.Name}, {fruit.Size}");
}
foreach (var fruit in fruits.Where(w => w.Size == "Small")) {
fruit.Size = "Large";
}
foreach (var fruit in fruits) {
Console.WriteLine($"Fruit Details After Update. {fruit.Name}, {fruit.Size}");
}
Console.ReadLine();
}
}
public class Fruit {
public string Name { get; set; }
public string Size { get; set; }
}
}输出结果
上面代码的输出是
Fruit Details Before Update. Apple, Small Fruit Details Before Update. Orange, Small Fruit Details Before Update. Mango, Medium Fruit Details After Update. Apple, Large Fruit Details After Update. Orange, Large Fruit Details After Update. Mango, Medium
在上面,我们仅过滤尺寸较小的水果并更新值。因此,where子句根据条件过滤记录。
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西