简体   繁体   中英

How to remove an string object from a list?

I have 2 list of String Header1 and Header2

List<String> Header1 = new List<String>();
Header1.add("String1");
Header1.add("String2");
Header1.add("String3");
Header1.add("String4");

and

    List<String> Header2 = new List<String>();
    Header2.add("STRING1");
    Header2.add("STRING2");

I would like to remove these entries "String1" and "String2" in Header2 from Header1 by ignoring the case sensitivity.

Any idea how to do it either using LINQ or string operation as well.

Thanks

Header1.RemoveAll(x => 
            Header2.Contains(x, StringComparer.CurrentCultureIgnoreCase));

There's no need for Linq. The List class has a convenient RemoveAll method you can use:

var stringsToRemove = new[] { "string1", "string2" };
var comp = StringComparison.InvariantCultureIgnoreCase;
Header1.RemoveAll(s => Header2.Any(t => s.Equals(t, comp)));

You can do:

Header1.Except(Header2, new EqualityComparer<string>((a, b) => a.Equals(b, StringComparison,OrdinalIgnoreCase)));

The EqualityComparer lets you specify a custom comparer so that it will only returns true when the string s are equal without considering the case.

MSDN documentation

I don't think LINQ allows you to modify collections. However, if you're happy to produce a new collection without the items from Header2, try something like this:

var result = Header1.Except(Header2, StringComparer.OrdinalIgnoreCase);

If you do want to modify the original list, try something like this:

Header1.RemoveAll(item => Header2.Contains(item, StringComparer.OrdinalIgnoreCase));

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