英文:
Is a C# Query needed to use the set operations?
问题
当我在寻找获取两个列表之间差异的方法时,我找到了这个页面:Set operations (C#)。
我发现我可以使用Except
方法。但是,这个代码示例中让我感到困惑的是:
string[] planets1 = { "Mercury", "Venus", "Earth", "Jupiter" };
string[] planets2 = { "Mercury", "Earth", "Mars", "Jupiter" };
IEnumerable<string> query = from planet in planets1.Except(planets2)
select planet;
foreach (var str in query)
{
Console.WriteLine(str);
}
/* This code produces the following output:
*
* Venus
*/
是这一行:IEnumerable<string> query = from planet in planets1.Except(planets2) select planet;
考虑到我对C#非常陌生,我的问题是,你需要使用这个查询来使用Except
方法吗?这一行似乎做了同样的事情:IEnumerable<string> query = planets1.Except(planets2);
我有什么遗漏吗?
英文:
When I was searching for a way to get the difference between two lists I came across this page: Set operations (C#).
I found out, that I can use the Except
method. But what confused me in this code example:
string[] planets1 = { "Mercury", "Venus", "Earth", "Jupiter" };
string[] planets2 = { "Mercury", "Earth", "Mars", "Jupiter" };
IEnumerable<string> query = from planet in planets1.Except(planets2)
select planet;
foreach (var str in query)
{
Console.WriteLine(str);
}
/* This code produces the following output:
*
* Venus
*/
was this line: IEnumerable<string> query = from planet in planets1.Except(planets2) select planet;
Considering that I’m very new to C#, my question is, do you need this query to use the Except method? This line seems to do the same thing: IEnumerable<string> query = planets1.Except(planets2);
Am I missing something here?
答案1
得分: 2
- 使用两种方式编写 LINQ 查询
- 查询表达式形式如下
IEnumerable<string> query = from planet in planets1.Except(planets2)
select planet;
- 方法链形式如下
IEnumerable<string> query = planets1.Except(planets2)
.Select(planet => planet);
在查询表达式形式中,必须存在 group 子句或 select 子句,但在方法链形式中,不需要以 select 方法结束。
因此,这两种代码都返回 IEnumerable<string[]>
。
planets1.Except(planets2)
和
planets1.Except(planets2).Select(planet => planet)
英文:
You can write LINQ in two way
-
query expression like form
IEnumerable<string> query = from planet in planets1.Except(planets2) select planet;
-
Method chain form
IEnumerable<string> query = planets1.Except(planets2) .Select(planet => planet);
In query expression form, group clause or select clause must exists but in method chain form you do not need to end with select method.
So both of these code return IEnumerable<string[]>
planets1.Except(planets2)
and
planets1.Except(planets2).Select(planet => planet)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论