简体   繁体   English

使用linq和c#

[英]Using linq with c#

I never used linq before but want to start using it in my code. 我之前从未使用过linq,但想在我的代码中开始使用它。

I have 2 string arrays. 我有2个字符串数组。

 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. 只是不知道如何使用linq做到这一点。

You can use Enumerable.Except which produces the set difference: 您可以使用Enumerable.Except来生成集合差异:

var rotten = allFruits.Except(healthyFruits);

If you need an array again use ToArray . 如果您需要再次使用数组,请使用ToArray

The Except extension method is certainly the best way to do what you're asking for, but strictly speaking it is not LINQ. Except扩展方法当然是做你要求的最好的方法,但严格来说它不是LINQ。 LINQ is "Language Integrated Query" and is the application of certainly extension methods in a way that they are integrated into the language. LINQ是“语言集成查询”,它是一种扩展方法的应用,它们被集成到语言中。

So, for example, to code your request using LINQ you would do this: 因此,例如,要使用LINQ对您的请求进行编码,您可以这样做:

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 我需要字符串[] rottenFruits

Create a new string array and fill it with allfruits, not included in healthyFruits and convert it to an array: 创建一个新的字符串数组并用allfruits填充它,不包含在healthyFruits中并将其转换为数组:

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

Don't forget to add: using System.Linq; 别忘了添加: using System.Linq; at the top of your class. 在你的班级顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM