1

Given a sequence of words with some repeated, such as this:

var words = "one two three two four five six four seven four eight".Split(' ');

You can find duplicates like this You can group the words like this:

var g1 = words.GroupBy(w => w);

I was trying to rewrite that into Linq Query sytnax, just to see what it looks like (I'm aware that in real code you would just leave it like the line above!).

The Linq I came up with looks far more complicated than it should, I think. How can it be simplified? And is it really the same as the line above?

var g2 = from w in words group w by w into g select g;

(I think I'm having a Sunday Brain-Fade... ;)

[EDIT] My source for this wonderment was from the answers to this question from earlier.

4

2 回答 2

5

您的查询不返回重复项,它返回不同的项目,因此您可以轻松使用 Distinct()扩展方法。

var dist = words.Distinct();

Distinct()在语法查询中没有等价物。

如果您真的要查找重复项,则必须将查询更改为:

var g1 = words.GroupBy(w => w).Where(g => g.Count() > 1).Select(g => g.Key);

并在语法查询中

var g1 = from w in words
         group w by w into g
         where g.Count() > 1
         select g.Key;

但是,第二个将由编译器翻译成第一个。

我没有看到任何更简单的方法来使用语法查询来获得它。

于 2013-04-14T09:18:57.697 回答
2

以上都是LINQ版本。一个是方法表达式,另一个是查询表达式。它们之间没有区别。

您应该看到:LINQ (C#) 中的查询语法和方法语法

如果您的意思是简化查询语法,那么我认为您不能对其进行太多修改,因为它等同于您的方法语法。

于 2013-04-14T09:17:40.253 回答