问题描述
我有一个字符串数组,f.e。
I have an array of strings, f.e.
string [] letters = { "a", "a", "b", "c" };
我需要找到一种方法来确定如果阵列中的任何字符串出现不止一次。
我认为最好的办法是让一个新的字符串数组,而不串中的问题,并使用包含
I need to find a way to determine if any string in the array appears more than once.I thought the best way is to make a new string-array without the string in question and to use Contains,
foreach (string letter in letters)
{
string [] otherLetters = //?
if (otherLetters.Contains(letter))
{
//etc.
}
}
但我无法弄清楚如何。
如果任何人有这个或解决方案,更好的方法,请回答。
but I cannot figure out how.If anyone has a solution for this or a better approach, please answer.
推荐答案
最简单的方法是使用的:
The easiest way is to use GroupBy
:
var lettersWithMultipleOccurences = letters.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
这将第一组用字母键阵列。然后,它返回仅与多个条目的集团和返回这些群体的关键。这样一来,你将有一个的IEnumerable<串>将含有所发生的原始数组中不止一次的所有字母
。在你的样品,这仅仅是A。
This will first group your array using the letters as keys. It then returns only those groups with multiple entries and returns the key of these groups. As a result, you will have an IEnumerable<string>
containing all letters that occur more than once in the original array. In your sample, this is only "a".
请注意:由于LINQ使用延迟执行,列举 lettersWithMultipleOccurences
多次执行,将执行分组和过滤多次。为了避免这种情况,调用了ToList()
的结果是:
Beware: Because LINQ is implemented using deferred execution, enumerating lettersWithMultipleOccurences
multiple times, will perform the grouping and filtering multiple times. To avoid this, call ToList()
on the result:
var lettersWithMultipleOccurences = letters.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key).
.ToList();
lettersWithMultipleOccurences
现在将类型列表与LT;字符串方式&gt;
这篇关于确定是否字符串多次出现在字符串数组(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!