Select the same item in the second list in the order of the second list
I have two lists of character arrays:
char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd'};
Now I want to get all the same item and get the same layout as in the second list ( : a, b, c, d ):
var final = charA.Where(x => charB.Any(y => y == x)).ToArray();
Result:
'a', 'd', 'd', 'b', 'c', 'a'
But what I want is a location in the second list using LINQ:
'a', 'a', 'b', 'c', 'd', 'd'
source to share
One way to achieve this is to select from a second array and join it first:
var result = from b in charB
join a in charA on b equals a into c
from a in c
select a;
You can also achieve this by attaching charA
to charB
and using an overload Select
that gets the index of the element:
var result = from a in charA
join b in charB.Select((item, index) => new { item, index }) on a equals b.item
orderby b.index
select a;
A little note on your implementation: see Contains
instead Any
:
charA.Where(x => charB.Contains(x))
source to share
Using method syntax:
char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd' };
var result = charA.Where(x => charB.Contains(x)).OrderBy(x => Array.IndexOf(charB, x));
First, it is Where
used to filter out values ββthat are not in charB
. Without this, items that are not in charB
end up at the beginning result
. The remaining collection is then simply sorted with Array.IndexOf
, which returns the index of each item charA
in charB
. This is not optimal, but a very short solution.
source to share