虽然我对此没有严格的要求,但我想操纵列表中除最后一个元素之外的所有元素。例如,假设一个类Cars
public class Car {
public string Name { get; set; }
public List<Tire> Tires { get; set; }
}
var cars = _db.GetAllCars().Select(x => new Car {
Name = x.Name + ", ",
Tires = x.Tires
});
这是有效的,除了列表中的最后一个元素将有一个逗号,我不想要...但我仍然想要列表中的最后一项。我不能这么简单的字符串。加入我将其传递给一个视图,该视图在Name元素周围有很多模板代码。我试图做的是什么?
答案 0 :(得分:4)
试试这个:
var cars = _db.GetAllCars().Reverse().Select((x, i) => new Car {
Name = x.Name + (i == 0 ? "" : ", "),
Tires = x.Tires
}).Reverse();
答案 1 :(得分:2)
改进版Lolo(在那里给点)
var cars = _db.GetAllCars().Select((x, i) => new Car {
Name = (i == 0 ? "" : ", ") + x.Name ,
Tires = x.Tires
});
答案 2 :(得分:0)
怎么样:
var allCars = _db.GetAllCars();
var cars = allCars.Select((x, i) => new Car { //where i is the index
Name = x.Name + (i != allCars.Count - 1 ? ", " : string.Empty), //or "." if you need a comma
Tires = x.Tires
});
修改强>
如上所述@newStackExchangeInstance,如果_db.GetAllCars()
返回ICollection
,则此方法有效,否则您需要将其转换为列表:
var allCars = _db.GetAllCars().ToList();
或者只使用Count()
扩展方法。
答案 3 :(得分:-1)
如果你真的想在从数据源检索后立即操作它:
var allCars = _db.GetAllCars().Select(x => new Car {
Name = x.Name,
Tires = x.Tires
}).ToList();
var cars = allCars.Take(allCars.Count() - 1).Select(x => new Car
{
Name = x.Name + ", ",
Tires = x.Tires
}).Concat(new[] { new Car {
Name = allCars.Last().Name,
Tires = allCars.Last().Tires
}});