![](/img/trans.png)
[英]How to get all elements except the n'th element in a List using Linq
[英]Perform manipulation on all elements except last element in a List using Linq
盡管我對此沒有嚴格要求,但我想操縱列表中除最后一個元素之外的所有元素。 例如,假設一個汽車類
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元素周圍的模板代碼的視圖。 我想做的事可能嗎?
嘗試這個:
var cars = _db.GetAllCars().Reverse().Select((x, i) => new Car {
Name = x.Name + (i == 0 ? "" : ", "),
Tires = x.Tires
}).Reverse();
Lolo的改進版本(在此處給出要點)
var cars = _db.GetAllCars().Select((x, i) => new Car {
Name = (i == 0 ? "" : ", ") + x.Name ,
Tires = x.Tires
});
關於什么:
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()
擴展方法。
如果您真的想在從數據源中檢索后立即對其進行操作:
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
}});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.