casillas
casillas

Reputation: 16793

Linq remove multiple objects

I could able to search for each item in the list and if that item exists, then I remove it from the list as follows.

However, instead of writing that many lines of code, I just wonder there is a better way doing it.

var math = subclasses.Classes.Where(x => x.Id.Equals(Constants.Classes.Math.ToString())).FirstOrDefault();
if (math != null) subclasses.Classes.Remove(math);

var chem= subclasses.Classes.Where(x => x.Id.Equals(Constants.Classes.Chem.ToString())).FirstOrDefault();
if (chem!= null) subclasses.Classes.Remove(chem);

var physics= subclasses.Classes.Where(x => x.Id.Equals(Constants.Classes.Physics.ToString())).FirstOrDefault();
if (physics!= null) subclasses.Classes.Remove(physics);

Upvotes: 0

Views: 205

Answers (3)

Sнаđошƒаӽ
Sнаđошƒаӽ

Reputation: 17552

2 steps:

  1. Write an overloaded version of Remove() that takes a List to remove. (Assuming the original Remove is your own implementation, and is a method of your class named Classes)
  2. Use Array.Contains() to get the list to remove

Something like this (on mobile, so...):

string [] mathChemPhy = new string []
{
    Constants.Classes.Math.ToString(),
    Constants.Classes.Chem.ToString(),
    Constants.Classes.Physics.ToString()
};

var itemsToRemove = subclasses.Classes.Where(x => mathChemPhy.Contains(x.Id)).ToList();
subclasses.Classes.Remove(itemsToRemove); // overloaded version of Remove that takes a list

Upvotes: 1

Slai
Slai

Reputation: 22866

You can remove them all without LINQ if Classes is a List<>:

subclasses.Classes.RemoveAll(x => x.Id.Equals(Constants.Classes.Math.ToString())
                               || x.Id.Equals(Constants.Classes.Chem.ToString())
                               || x.Id.Equals(Constants.Classes.Physics.ToString()));

Upvotes: 3

Alpha75
Alpha75

Reputation: 2280

You can use Except extension method:

var exceptions = subclasses.Classes.Where(x => x.Id.Equals(Constants.Classes.Math.ToString() 
    || x.Id.Equals(Constants.Classes.Chem.ToString() 
    || x.Id.Equals(Constants.Classes.Physics.ToString());
var result = subclasses.Classes.Except(exceptions);

Upvotes: 1

Related Questions