Steve
Steve

Reputation: 352

To remove an item in List

I am trying to remove an item in my gcNumber but it is not getting removed. Below is my code. i know i am doing some silly thing but don't know where :(

 var gcn=gcNumber.ToList();
 foreach (var selectGc in gcn)
   {                
        var countToRemove = _uow.GetRepository<TripSheetGcDetail>().GetAll().Where(x => x.FkGcId == selectGc.Id && x.IsActive == true).Select(y => y);
        if(countToRemove .Count()>0)
        {                   
            gcNumber.ToList().Remove(selectGc);
        }
        else
        {
        }

   }
    return gcNumber.ToList();

if my CountToRemove.count()>0 then i want to remove that item in my gcNumber list. Kindly help where i am doing wrong.

Upvotes: 0

Views: 204

Answers (3)

MKasprzyk
MKasprzyk

Reputation: 499

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public class MyClass
    {
        public string Name {get; set;}  
    }

    public static void Main()
    {

        var list = new List<MyClass>();

        list.Add(new MyClass() {Name = "aaa"});
        list.Add(new MyClass() {Name = "bbb"});
        list.Add(new MyClass() {Name = "ccc"});
        list.Add(new MyClass() {Name = "ddd"});

        var indexesToRemove = new List<int>();

        foreach(var item in list)
        {
                if(item.Name == "aaa")
                    indexesToRemove.Add(list.IndexOf(item));
        }

        foreach (var num in indexesToRemove)
            list.RemoveAt(num);


            Console.WriteLine(list.First().Name);

    }
}

Maby it is not the best way to remove items from list but it's clear. You can't remove items form list which is enumerating.

Upvotes: 0

Colin Mackay
Colin Mackay

Reputation: 19175

gcNumber.ToList().Remove(selectGc);

This line creates a new list, which you remove stuff from, then since you don't do anything else (like assign the list any where) throws the modified list away.

I'm guessing what you want to do instead is something like:

gcn.Remove(selectGc);

You also want to modify your foreach so that it isn't looping over something that is getting modified.

foreach(var selectGg in gcNumber)

This will loop over the original thing, allowing you to modify the copy.

And you'll probably want to return gcn, as your return statement just creates another new list based on gcNumber which hasn't been modified.

In summary: .ToList() creates a new list every time, so modifying that list won't do anything to the original.

Upvotes: 1

Megha shah
Megha shah

Reputation: 232

instead of gcNumber.ToList().Remove(selectGc); just do gcNumber.Remove(selectGc);

Upvotes: 1

Related Questions