繁体   English   中英

多个字符串中的不同字符

[英]Distinct characters across multiple strings

我正在尝试在列表中的所有字符串中获取不同的字符列表(区分大小写)。

我有一个包含3个字符串的列表:

"AABbDDCCRRFF"
"JOJaCK"
"BILLY"

输出应该是(字符的顺序并不重要):

ABDCRFJOKaILYb

我知道下面的内容有误,但无法解决:

            distChars = (from string row in valuesList[c]
                         select row.Distinct()
                         ).Distinct().ToString();

有谁知道如何从每个字符串中返回不同的字符。 如果在LINQ中无法做到这一点,那么我愿意接受替代方案。 谢谢!

更新:哇,很棒的答案,这么快! 按字母顺序或按出现频率排序字符的方法是什么?

你可以这样做:

string[] values = new []{"AABbDDCCRRFF","JOJaCK","BILLY"};

var uniqueChars = new string(values.SelectMany(x => x).Distinct().ToArray());

编辑:

正如@Douglas所建议的那样,使用string.Concat()而不是new string()可能会稍微提高效率,即:

var uniqueChars = string.Concat(values.SelectMany(x => x).Distinct());

尝试这个;

var valuesList = new List<string> {"AABbDDCCRRFF", "JOJaCK", "BILLY"};

var distChars = string.Join("", (from str in valuesList  // Select all strings.
                                 from ch in str          // Select all chars.
                                 select ch).Distinct()); // Get distinct chars.

在代码中,你第一次从每行选择不同的字符,然后选择字符的不同序列 ,最后调用ToStringIEnumerable<T>

我建议您先从所有行中选择所有字符,对组合序列应用Distinct过滤器,最后调用string.Concat来连接生成的字符序列:

var distChars = string.Concat(
    (
        from row in valuesList[c]
        from c in row
        select c
    ).Distinct());

你想拥有不同的字符而不是字符串。

var strings = new string[] { "AABbDDCCRRFF", "JOJaCK", "BILLY" };
var q = (from str in strings
         from c in str
         select c).Distinct().ToList();

这里的问题是你有一个集合的集合。 在选择不同的字符之前尝试连接字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM