在一般情况下,您可以在Linq Aggregate
的帮助下对字符串(lines
)进行query.请注意,要从枚举(IEnumerable<char>
)中获取字符串,我们应该使用Concat()
,而不是ToString()
:
using System.Linq;
...
// Organize the strings into a collection, say, an array
// (Set, List etc. will do as well)
string[] lines = {
"vJrwpWtwJgWrhcsFMMfFFhFp",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL",
"PmmdzqPrVvPwwTWBwg",
};
...
// Query the collection above with a help of Linq:
// We turn each string into enumeration (IEnumerable<char>)
// Aggregate all enumerations into one with a help of Intersect
// Concat characters of the final enumeration to the string
string commonString = string.Concat(lines
.Select(line => line.AsEnumerable()) // we deal with IEnumerable<char>, not string
.Aggregate((s, a) => s.Intersect(a))
.OrderBy(c => c) // In case you want common characters being ordered
);
如果字符串中可以出现null
,则将.Select(...)
更改为
.Select(line => line?.AsEnumerable() ?? Array.Empty<char>())
拜托,fiddle个你自己.
如果您只想让三个字符串相交,则可以按如下方式操作:
string first = "vJrwpWtwJgWrhcsFMMfFFhFp";
string second = "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL";
string third = "PmmdzqPrVvPwwTWBwg";
string commonString = string.Concat(first
.Intersect(second)
.Intersect(third));