gpt4 book ai didi

c# - 使用 LINQ 更改集合中的项目

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

我有以下代码:

List<Car> allCars = new List<Car>
{
new Car(1977, "Ford", "Pinto"),
new Car(1983, "Ford", "Taurus"),
new Car(1981, "Dodge", "Colt"),
new Car(1982, "Volkwagen", "Scirocco"),
new Car(1982, "Dodge", "Challenger")
};

Array.ForEach(allCars.ToArray(), Console.WriteLine);

// I want to do an "in-place" modification of an item in
// the list
var query = allCars.Select(x =>
{
if (x.Model == "Colt") return "Dart";
});

public class Car
{
public int Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }

public Car(int year, string make, string model)
{
Year = year; Make = make; Model = model;
}

public override string ToString()
{
return string.Format("{0} - {1} {2}", Year, Make, Model);
}
}

现在我知道我可以做到:

var query = allCars.Select(c => c.Model == "Colt");

或者这个:

for (var item in allCars.Select(c => c.Model == "Colt"))
{
item.Model = "Dart";
}

或者这个:

allCars.Single(c => c.Model == "Colt").Model = "Dart";

但是如何“就地”修改列表中的项目呢?

如果我有一个属性要修改,我提到的最后一种方法可以正常工作,但如果我有两个呢?

最佳答案

LINQ 是一种查询语言,它应该保持原始集合不可变。

没关系

foreach (var item in allCars.Where(c => c.Model == "Colt"))
{
item.Model = "Dart";
}

请阅读this post on why it is not implemented in LINQ

关于c# - 使用 LINQ 更改集合中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14653462/

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