tags:

views:

439

answers:

3

I have 2 collections, one of available features and one of user features. I would like to delete an item in the available features that contain the featurecode in the other collection but can't find the right syntax.

I've included my current code that doesn't compile (it's complaining that I can't use the "==" operator, my Linq knowledge is minimal)

Is Linq the best way to do this? Any help would be appreciated.

        AvailableFeatureViewListClass availableFeatures = (AvailableFeatureViewListClass)uxAvailableList.ItemsSource;
        UserFeatureListClass userFeatures = (UserFeatureListClass)uxUserFeatureList.ItemsSource;

        foreach (UserFeatureClass feature in userFeatures)
        {
            availableFeatures.Remove(availableFeatures.First(FeatureCode => FeatureCode == feature.FeatureCode));
        }
+4  A: 

Use Except method with a custom Equals or IEqualityComparer implementation for your type (the type of your collection item is not really obvious):

var features = availableFeatures.Except(userFeatures, new FeatureCodeComparer());

If the availableFeatures is just a collection of integers, you'd just do something like:

var features = availableFeatures.Except(userFeatures.Select(x => x.FeatureCode));
Mehrdad Afshari
I tried the second suggestion and it complains that the "x" part cannot be inferred. Sounds like it should work but the Linq is throwing me right now.
Mark Kadlec
@Mark: Could you tell us what the `AvailableFeatureViewListClass` or `UserFeatureListClass` types are? Why aren't you just using generic types directly?
Mehrdad Afshari
Thanks Mehrdad, they are actually both BusinessObjects, but the items in the object collection share properties (in this case FeatureCode)
Mark Kadlec
It looks weird that the compiler can't infer the type in an standard environment. But anyway, try changing the lambda to (TypeOfYourObjectGoesHere x) => x.FeatureCode
Mehrdad Afshari
+1  A: 

Try something like this:

var features = (from af in availableFeatures select af.FeatureCode)
         .Intersect(from uf in userFeatures select uf.FeatureCode);
Andrew Hare
Thanks Andrew, it looks right but when I try to bind nothing returns. I checked and the features variable is cast to the IntersectIntegrator object, is there any way to convert that back to a AvailableFeatureViewList class?
Mark Kadlec
A: 

How about this?

    IEnumerable<int> a = new List<int>() { 1, 2 };
    IEnumerable<int> b = new List<int> { 2, 3 };

    var result = a.Except(b);
    a = result;
Senthil Kumar