简体   繁体   中英

Comparing two collections of objects

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

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

Try something like this:

var features = (from af in availableFeatures select af.FeatureCode)
            .Intersect(from uf in userFeatures select uf.FeatureCode);

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;

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