Search code examples
c#exceptselectlistitem

I tried to do a "Except()" but it did not work


Possible Duplicate:
how can I do use Except() between two SelectListItem lists

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 it did not work

Example code:

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


Solution

  • This should work, take alook at this example:

                double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
                double[] numbers2 = { 2.2 };
    
                IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
    
                foreach (double number in onlyInFirstSet)
                    Console.WriteLine(number);
    
                /*
                 This code produces the following output:
    
                 2
                 2.1
                 2.3
                 2.4
                 2.5
                */
    

    I guess the problem is that the Equality comparer in your case (for SelectedListItem) isnt defined, or better said things which look the same are not simply the same objects, in this case you will have to provide the [IEqualityComparer] to define which elements are actually equal1:

    public static IEnumerable<TSource> Except<TSource>(
        this IEnumerable<TSource> first,
        IEnumerable<TSource> second,
        IEqualityComparer<TSource> comparer
    )