Ad

How To Remove All Next Elements From List Of Object On Condition In C#

- 1 answer

I have one list of objects

public class Card
{
    public int Id { get; set; }
    public double Price { get; set; }
    public string Name{ get; set; }
}

How to remove all next elements from list when there is a match on condition something like-

if(object1.Price== 0)
{
  //remove all next elements from list
}

I want to keep the list from 0 to matching position like if price is zero at index 5 then take 0 to 5 elements.

Ad

Answer

If you are using a List<T> where T is Card you can use List<T>.FindIndex to get the index of the first element matching the predicate and get the range of the List:

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; }
} 
Ad
source: stackoverflow.com
Ad