简体   繁体   中英

How to remove instances from a List, which don't contain objects that match values from a Dictionary?

I came up with this, using LINQ:

records.RemoveAll(x => 
    !(x.MyList.Contains(values[0]) || x.MyList.Contains(values[1]) || x.MyList.Contains(values[2]) || ... )
);
  • records is a List<CustomObject> , that has a List<string> MyList
  • values is an OrderedDictionary , though it could easily be a Dictionary<string,string> instead, if there is a solution that doesn't require accessing it by index.

My problem with this code is that I don't know the size of values ahead of time, and can't hardcode it like this. Is there a way to use a for or foreach loop here? Or, how else can I achieve this line of code?

I think it will be something like

records.RemoveAll(x => 
    !(values.Any(v=>x.MyList.Contains(v)))
);

Try this:

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()));
}

这也可以...

records.Except(values.Select(v => v.Value)).ToList().ForEach(a => records.Remove(a.ToString())) ;

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