使用LINQ更改集合中的项目

时间:2013-02-01 19:16:49

标签: c# linq

我有以下代码:

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";

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

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

2 个答案:

答案 0 :(得分:14)

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

这没关系

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

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

答案 1 :(得分:1)

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