我想出了这个,使用LINQ:
records.RemoveAll(x =>
!(x.MyList.Contains(values[0]) || x.MyList.Contains(values[1]) || x.MyList.Contains(values[2]) || ... )
);
records
是List<CustomObject>
,有List<string> MyList
values
是一个OrderedDictionary
,但如果有一个解决方案不需要通过索引访问它,它可以很容易地成为Dictionary<string,string>
。我对此代码的问题是我提前知道values
的大小,并且不能像这样硬编码。有没有办法在这里使用for或foreach循环?或者,我还能如何实现这一行代码呢?
答案 0 :(得分:3)
我认为它会像
records.RemoveAll(x =>
!(values.Any(v=>x.MyList.Contains(v)))
);
答案 1 :(得分:2)
试试这个:
var values = new OrderedDictionary()
{
{ "A", null },
{ "B", null },
{ "C", null },
{ "D", null },
{ "E", null },
};
var records = new List<CustomObject>
{
new CustomObject{ Id = 1, MyList = new List<string>(){ "A", "B" }},
new CustomObject{ Id = 2, MyList = new List<string>(){ "C", "F" }},
new CustomObject{ Id = 3, MyList = new List<string>(){ "G", "H" }}
};
records.RemoveAll(record => !record.MyList.Any(item => values.Contains(item)));
foreach (var record in records)
{
Console.WriteLine("Id={0}, MyList={1}",
record.Id, String.Join(", ", record.MyList.ToArray()));
}
答案 2 :(得分:0)
这也有效......
records.Except(values.Select(v => v.Value)).ToList().ForEach(a => records.Remove(a.ToString())) ;