SuicideSheep
SuicideSheep

Reputation: 5550

IEnumerable Best Practice of removing int item

I have a IEmunerable list with N items for example: 23, 1, 38.....

The needed logic is, when looping thru the list:

1: find if 1exist

2: if 1 exist, find 2

3: if 2 exist, find 3

4: If 3 exist, remove 3 from the current list.

My current approach is:

foreach(var x in someIntList)
{
    if(x==1)
    {
        if(someIntList.Any(y => y==2))
        {
            if(someIntList.Any(z => z==3))
            {
                //This is the shortest code i can think of, but apparently its wrong. Error saying there is no Except method for IEmunerable<Int> ?
                someIntList = someIntList.Except(3);

            }

        }

    }   

}

Upvotes: 0

Views: 460

Answers (3)

woutervs
woutervs

Reputation: 1510

Snippet

var x = new List<int> {5, 4, 3, 2, 1};
        if(x.Contains(1) && x.Contains(2) && x.Contains(3)) x.Remove(3);

Just in case...

IEnumerable<int> y = new List<int> {5,4,3,2,1};

So if you are getting an IEnumerable from your method.

var x = y.ToList()

If you need to remove all, x.RemoveAll(z=>z == 3);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500635

It's not clear why you're looping to start with, or using Any instead of Contains:

if (someIntList.Contains(1) && someIntList.Contains(2) && someIntList.Contains(3))
{
    someIntList = someIntList.Where(x => x != 3); // Possibly with ToList()?
}

You probably don't want to use Except as that's a set-based operation - if your original list contains duplicates, they will be removed if you use Except.

Note that this will remove all occurrences of 3 - is that what you want, or do you just want to remove the first occurrence of 3?

Upvotes: 1

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

You need to pass IEnumerable<int> to except, like this

someIntList = someIntList.Except(new[] {3});

read more about Except on MSDN

To remove better use this, I can't imagine shorter version:

if(someIntList.Contains(1)&&someIntList.Contains(2)&&someIntList.Contains(3))
{
    someIntList.Remove(3); // **if it's a list**
    someIntList = someIntList.Except(3); //**if it's a IEnumerable**
}

Upvotes: 2

Related Questions