Ave
Ave

Reputation: 4430

How to delete one items in List C#?

I have List<String> include nine items.

I want to delete at item contains: &nbsp;.

I do this with code:

foreach (string text in listHeader[0])
{
    if (text.Contains("&nbsp"))
    {
        listHeader[0] = listHeader[0].SelectMany(line =>
                                       {
                                           line.Replace("&nbsp;", "");
                                           return new String[] { line };
                                       }).ToList();
    }
}

But listHeader[0] also have nine items. How to fix my code to delete item contains &nbsp;.

Sample data:

listHeader[0]= {
                   text
                   sample
                   new string
                   &nbsp;
               }

Another case my listHeader[1] need filter with start with <!--<div to </div>-->.

foreach (string text in listHeader[1])
{
    listHeader[1] = Regex.Replace(text, "<!--<div.*?</div>-->", "").ToList();
}

My question is:

How to remove item contains string start with <!--<div and end at </div>-->

Sample:

listHeader[1] = {
go to school

<!--<div id='fav_0118668891'class='icon displayOn' ><span class='favorite' onclick='javascript:addMatchFavorites("0118668891","014018",false,false);' title='undefined'></span></div>-->

work at the company

take a coffee
}

My resolve:

In this case:

I using StartWith and EndWith to find this string and Remove.

listHeader[1].RemoveAll(x => x.StartsWith("<!--<div") && x.EndsWith("</div>-->"));

Upvotes: 1

Views: 70

Answers (2)

Hari Prasad
Hari Prasad

Reputation: 16956

How to fix my code to delete item contains &nbsp;

You could use List.RemoveAll method which removes all the elements that match the conditions defined by the specified predicate.

listHeader[0].RemoveAll(x=> x.Contains("&nbsp"));

Check this Demo

Upvotes: 3

gotnull
gotnull

Reputation: 27214

foreach (var item in listHeader[0])
{
    if (item.Contains("&nbsp"))
        nineItems.Remove(item); // remove item(s) containing &nbsp
}

OR a simpler way:

listHeader[0].RemoveAll(x => x.Contains("&nbsp"));

Upvotes: 3

Related Questions