T
T
tera10042019-02-21 19:42:02
C++ / C#
tera1004, 2019-02-21 19:42:02

Removing an element in List C#?

How to update a list of elements that no longer contains an element with the specified sequence number?

public static Payment ClearPayment()
        {
            Console.Write("Enter code: ");
            int C = int.Parse(Console.ReadLine());
            var found = payments.Exists(c => c.Code == C);
            
            if (found == true)
            {
                foreach (Payment n in payments)
                {
                    payments.RemoveAt(C-1);
                }
            }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Foggy Finder, 2019-02-21
@tera1004

You can use the RemoveAll method to remove all occurrences that match the passed predicate:

public static void ClearPayment()
{
    Console.Write("Введите код: ");
    int C = int.Parse(Console.ReadLine());
    if (payments.RemoveAll(p => p.Code == C) > 0)
        Console.WriteLine("Указанный платеж удален ");
    else
        Console.WriteLine("Платежа с таким кодом не существует");
}

RemoveAll will return the number of elements that have been removed from the list.
Another way is to use a combination of methods from the Find and Remove group:
FindIndex + RemoveAt
or
Find + Remove
The difference from Exists is that these methods return the index (FindIndex) or the element itself (Find), and not just check the existence of a suitable element.

J
John_Nash, 2019-02-21
@John_Nash

foreach (Payment n in payments)
{
payments.RemoveAt(C-1);
}

foreach (Payment n in payments.ToList())
{
payments.RemoveAt(C-1);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question