简体   繁体   中英

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>-->"));

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

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM