# Find common characters from group of string

## Find common characters from group of string

Contents

Problem Description:

Given the set of below strings

``````vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
``````

In above strings only lower case letter `"r"` is common in all of them.

I know we can use `Intersect`to find common things in 2 string but how to do using 3 strings?

This code below i did for 2 strings

``````var commonString = firstPartOfstring
.Intersect(secondPartOfString)
.Select(x => x)
.FirstOrDefault()
.ToString();
``````

But cant find how to do for 3 strings

## Solution – 1

Intersect is transitive — that means you can string them together in sequence.

``````var commonString = firstPartOfstring
.Intersect(secondPartOfString)
.Intersect(thirdPartOfString)
.Select(x => x).FirstOrDefault().ToString();
``````

(nb – you can sequence them in any order – the other attribute of transitive)

## Solution – 2

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>())
``````

``````string first = "vJrwpWtwJgWrhcsFMMfFFhFp";