如何在c#中获取不同的字符

Dom*_*nic 25 c#

我有一个代码

string code = "AABBDDCCRRFF";
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我想只检索不同的字符

输出应该像:

ANS: ABDCRF
Run Code Online (Sandbox Code Playgroud)

Rob*_*Day 38

string code = "AABBDDCCRRFF";
string answer = new String(code.Distinct().ToArray());
Run Code Online (Sandbox Code Playgroud)

  • `string`已经实现了`IEnumerable <char>`所以你可以删除对`ToCharArray()`的调用. (2认同)

Geo*_*ord 10

Linq的Distinct返回序列中不同的元素.在String类实现时IEnumerable<char>,Distinct在此上下文中返回IEnumerable<char>包含字符串中所有唯一字符的内容.

code.Distinct();
Run Code Online (Sandbox Code Playgroud)