0

我想出了这个,使用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是 a ,但如果有不需要通过索引访问它的解决方案,OrderedDictionary它很容易改为 a 。Dictionary<string,string>

我对这段代码的问题是我不知道values提前的大小,也不能像这样硬编码它。有没有办法在这里使用 for 或 foreach 循环?或者,我还能如何实现这行代码?

4

3 回答 3

3

我想它会是这样的

records.RemoveAll(x => 
    !(values.Any(v=>x.MyList.Contains(v)))
);
于 2013-06-05T19:35:28.353 回答
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()));
}
于 2013-06-05T19:41:20.630 回答
0

这也有效...

records.Except(values.Select(v => v.Value)).ToList().ForEach(a => records.Remove(a.ToString())) ;
于 2013-06-05T19:39:51.373 回答