[英]How to remove all next elements from list of object on condition in c#
我有一個對象列表
public class Card
{
public int Id { get; set; }
public double Price { get; set; }
public string Name{ get; set; }
}
當條件匹配時如何從列表中刪除所有下一個元素 -
if(object1.Price== 0)
{
//remove all next elements from list
}
我想將列表從 0 保持到匹配 position 就像如果價格在索引 5 處為零,則取 0 到 5 個元素。
您可以使用TakeWhile
和Select
的組合,例如:
var lst = new List<Card>() {
new Card() { Price = 2 },
new Card() { Price = 1 },
new Card() { Price = 0 },
new Card() { Price = -1 },
new Card() { Price = -2 },
};
var found = false;
var items = lst.TakeWhile(x => !found).Select(x =>
{
if (x.Price == 0)
found = true;
return x;
});
這導致價格為 2、1、0 的項目被保留,而 -1 和 -2 被刪除。
請參閱此小提琴進行測試。
如果您使用List<T>
其中T
是Card
您可以使用List<T>.FindIndex
來獲取與謂詞匹配的第一個元素的索引並獲取列表的范圍:
List<Card> cards = new List<Card> { new Card {Id = 1, Price = 1.0, Name = "Ace" },
new Card {Id = 2, Price = 0.0, Name="Two" }};
Predicate<Card> test1 = a => a.Price == 1.0;
Predicate<Card> test2 = b => b.Price == 0.0;
//You can also do something like this:
Predicate<Card> test3 = c => c.Price == 1.0 && c.Id == 1;
Console.WriteLine(GetCardRange(cards, test1).Count); //Prints 1
Console.WriteLine(GetCardRange(cards, test2).Count); //Prints 2
Console.WriteLine(GetCardRange(cards, test3).Count); //Prints 1
//or shorthand without declaring a Predicate:
Console.WriteLine(GetCardRange(cards, (a) => a.Price == 0.0).Count); //Prints 2
//Method accepts a predicate so you can pass in different
//types of condition(s)
public List<Card> GetCardRange(List<Card> cards, Predicate<Card> p)
{
int index = cards.FindIndex(p);
//if no card is found, either return the whole list
//or change to return null or empty list
return index == -1 ? cards :
cards.GetRange(0, index + 1);
}
public class Card
{
public int Id { get; set; }
public double Price { get; set; }
public string Name{ get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.