how can I do use Except() between two SelectListIt

2019-01-29 15:00发布

问题:

I have two list of type IEnumerable <SelectListItem> I need to create a new IEnumerable <SelectListItem> with the elements of the first list that do not exist in the second list. how can i do this?

I tried to do it with a Except() but did not result...

Example code:

IEnumerable<SelectListItem> SelectListItemA = ....;
IEnumerable<SelectListItem> SelectListItemB = ....;
IEnumerable<SelectListItem> Except = SelectListItemA.Except(SelectListItemB);

回答1:

Maybe something like:

var items1 = new List<SelectListItem>();
var items2 = new List<SelectListItem>();
//[.. populate lists here ..]
var onlyInFirst = items1.RemoveAll(item1 => items2.Any(item2 => item1.Value == item2.Value));

Except requires that Equals and GetHashCode is implemented in the traversed class.