从字符串保存重复值

时间:2016-10-31 15:36:30

标签: c# .net linq

我有:

string turtle = "turtle"
var charArray = turtle.ToCharArray()

当我这样做时:

var distinct = charArray.Distinct().ToArray()
// distinct = ["t","u","r","l","e"]

我的问题是:

当我打电话给Distinct时,如何保存从charArray删除的字符?如何使变量distinct等于"t"(已删除的字符)

谢谢!

2 个答案:

答案 0 :(得分:2)

使用GroupBy仅返回字母having count > 1

string turtle = "turtle";
var dups = (from l in turtle
            group 1 by l into g
            where g.Count() > 1
            select g.Key).ToList();

答案 1 :(得分:1)

var nonUniqueChars = charArray.GroupBy(x => x)
.Where(x => x.Count() > 1)
.Select(x => x.First())

这将组织所有出现的字符组,找到多次出现的字符,然后拉出每个这样的字符的单个实例。