如何从List中删除实例,这些实例不包含与Dictionary中的值匹配的对象?

时间:2013-06-05 19:32:20

标签: c# linq list dictionary

我想出了这个,使用LINQ:

records.RemoveAll(x => 
    !(x.MyList.Contains(values[0]) || x.MyList.Contains(values[1]) || x.MyList.Contains(values[2]) || ... )
);
  • recordsList<CustomObject>,有List<string> MyList
  • values是一个OrderedDictionary,但如果有一个解决方案不需要通过索引访问它,它可以很容易地成为Dictionary<string,string>

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

3 个答案:

答案 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())) ;