简体   繁体   中英

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.

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

var rotten = allFruits.Except(healthyFruits);

If you need an array again use ToArray .

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. :-)

试试这样

var fruits = allFruits.Except(healthyFruits);

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.

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