In general case you can query the strings (lines
) with a help of Linq Aggregate
. Please, note, that to get string from enumeration (IEnumerable<char>
) we should use Concat()
, not 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
);
if null
can appear among the strings, change .Select(...)
into
.Select(line => line?.AsEnumerable() ?? Array.Empty<char>())
Please, fiddle youself.
If you want just to intersect three strings you can do it as follow:
string first = "vJrwpWtwJgWrhcsFMMfFFhFp";
string second = "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL";
string third = "PmmdzqPrVvPwwTWBwg";
string commonString = string.Concat(first
.Intersect(second)
.Intersect(third));