Mathematics
Mathematics

Reputation: 7618

Using linq with c#

I never used linq before but want to start using it in my code.

I have 2 string arrays.

 string[] allFruits = allFruitTextHiddenBox.Text.Value.Trim('|').Split('|');
 string[] healthyFruits = GetHealthyFruits().Trim('|').Split('|');

 // now I need to get rotten fruits which are ones  allfruit - healthyfruits

 // I need string[] rottenFruits please

Just not sure how to do it using linq.

Upvotes: 2

Views: 90

Answers (4)

Enigmativity
Enigmativity

Reputation: 117027

The Except extension method is certainly the best way to do what you're asking for, but strictly speaking it is not LINQ. LINQ is "Language Integrated Query" and is the application of certainly extension methods in a way that they are integrated into the language.

So, for example, to code your request using LINQ you would do this:

var query =
    from fruit in allFruits
    where !healthyFruits.Contains(fruit)
    select fruit;

var results = query.ToArray();

Just being a bit nit-picky. :-)

Upvotes: 3

Max
Max

Reputation: 13338

Now I need to get rotten fruits which are ones allfruit - healthyfruits
I need string[] rottenFruits please

Create a new string array and fill it with allfruits, not included in healthyFruits and convert it to an array:

string[] rottenFruits = allFruits.Except(healthyFruits).ToArray();

Don't forget to add: using System.Linq; at the top of your class.

Upvotes: 1

try like this

var fruits = allFruits.Except(healthyFruits);

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use Enumerable.Except which produces the set difference:

var rotten = allFruits.Except(healthyFruits);

If you need an array again use ToArray.

Upvotes: 7

Related Questions