C# C.Where&。挑选
我正在研究如何检查字符重复,我遇到了这个方法,它是有效的,但我试图了解它是如何工作的。如果有人能解释这种方法,以便我能更好地理解正在发生的事情,我将不胜感激。多谢各位C# C.Where&。挑选,c#,C#,我正在研究如何检查字符重复,我遇到了这个方法,它是有效的,但我试图了解它是如何工作的。如果有人能解释这种方法,以便我能更好地理解正在发生的事情,我将不胜感激。多谢各位 static int duplicateAmount(string word) { var duplicates = word.GroupBy(a => a) .Where(g => g.Count() > 1) .Select(i => new { Number =
static int duplicateAmount(string word)
{
var duplicates = word.GroupBy(a => a)
.Where(g => g.Count() > 1)
.Select(i => new { Number = i.Key, Count = i.Count() });
return duplicates.Count();
}
当您迭代一个字符串时,可以通过迭代它的所有
char
acter来实现
因此:
static int duplicateAmount(string word)
{
var duplicates = word.GroupBy(a => a) // Groups all the unique chars
.Where(g => g.Count() > 1) // filters the groups with more than one entry
// Maps the query result to an anonymous object containing the char
// and their amount of occurrences
.Select(i => new { Number = i.Key, Count = i.Count() });
// return the count of elements in the resulting collection
return duplicates.Count();
}
现在您已经了解了这一点,您可能会知道最后一步(映射)是不必要的,因为我们正在创建一个根本不使用的结构:{Number,Count}
代码完全可以是
static int duplicateAmount(string word)
{
return word.GroupBy(a => a) // Groups all the unique chars
// Counts the amount of groups with more than one occurrence.
.Count(g => g.Count() > 1);
}
已编辑:删除注释中注明的where子句。感谢@DrkDeveloper我们的想法是对字符串中的字符进行分组,并检查是否有任何组包含多个元素,这表示字符重复出现。例如
word.GroupBy
将产生如下分组结果
正如您所观察到的,字符t、i和s有多处出现。Where条件过滤具有多个元素的组,count方法统计过滤组的数量
在您的例子中,如果您只对重复的字符数感兴趣,您可以根据需要进一步重构该方法
static int duplicateAmount(string word)
{
return word.GroupBy(a => a)
.Count(g => g.Count() > 1);
}
这避免了创建中间类型,如果您只对计数感兴趣,则不需要创建中间类型。我认为,对于这种方法,您不需要Where和Select,您可以在一行中完成:word.GroupBy(a=>a).count(g=>g.count()>1)<代码>其中是不必要的,并进行另一次完整迭代<代码>GroupBy(a=>a).Count(g=>g.Count()>1)代码>是的,你完全正确。老实说,我专注于解释,却完全忽略了这一点。我会编辑它,这样其他人就不会上当了。是的,这是最短也是最理想的Linq答案。