我有一个List<T>
,其中T有一个字符串属性,我们称之为Value
然后我有List<string>
包含一些关键字。
如何删除List<T>
中属性值与List<string>
中的一个关键字匹配的所有项目?
答案 0 :(得分:3)
使用List<T>.RemoveAll Method (Predicate<T>)
,谓词检查关键字列表是否包含值。
示例控制台应用程序:
public static class Program
{
public class A
{
public string Value { get; set; }
}
public static void Main(string[] args)
{
var keywords = new List<string>() {"A", "B", "C", "D"};
var aas = new List<A>()
{
new A() {Value = "A"},
new A() {Value = "AA"},
new A() {Value = "B"},
new A() {Value = "AB"}
};
Console.WriteLine("Before remove:");
aas.ForEach(a => Console.WriteLine(" A.Value = {0}", a.Value));
aas.RemoveAll(a => keywords.Contains(a.Value));
Console.WriteLine("After remove:");
aas.ForEach(a => Console.WriteLine(" A.Value = {0}", a.Value));
}
}
输出控制台:
Before remove:
A.Value = A
A.Value = AA
A.Value = B
A.Value = AB
After remove:
A.Value = AA
A.Value = AB
答案 1 :(得分:1)
public class test
{
public string waarde { get; set; }
}
class Program
{
static void Main(string[] args)
{
var teBeRemoved = new List<string> {"een", "twee"};
var totalList = new List<test> { new test { waarde = "een" }, new test { waarde = "drie" } };
var filteredList = totalList.Where(i => !teBeRemoved.Contains(i.waarde));
}
}