0

So essentially I have a rainbow with Red, Orange, Yellow, Green, Blue, Indigo and Violet. Let's make this an array.

var rainbowArray = new string[] {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};

Now I have a second array that is unordered and comes from the database. This array contains:

var databaseArray = new string[] { "yellow", "red", "indigo" }

How can I order the second array to be in the same order as the first array. We can always assume that the "main" (first) array has all the items that the database will return.

1
  • Please provide an example of the desired result. Commented Nov 9, 2020 at 10:01

3 Answers 3

4

Using a combination of Enumerable.OrderBy and Array.IndexOf:

databaseArray.OrderBy(x => Array.IndexOf(rainbowArray, x));

This follows your assertion that all items in the second array will be in the first array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! This is exactly what I want and very clean with a one liner.
3

under you assumption: We can always assume that the "main" (first) array has all the items that the database will return

you can do

rainbowArray.Intersect(databaseArray)

which is the nicest way.

2 Comments

also like this version, but I accepted the other answer because it actually sorts. I looked the intersect documentation up but this isn't made for sorting, even if it can be used like it. Thanks a lot tho!
sure Intersect is not made for sorting but it keeps original collection order. so under your assumption I suggested this solution. of course this is not a general solution. just for you specific case.. :)
0

It's not clean, but it's work :)

var rainbowArray = new string[] { "red", "orange", "yellow", "green", "blue", "indigo", "violet" };

var databaseArray = new string[] { "yellow", "red", "indigo" };

List<string> testArray = new List<string>();
foreach(var item in rainbowArray)
{
      if(databaseArray.Contains(item))
      {
         testArray.Add(item);
      }
 }

var endArray = testArray.ToArray();

1 Comment

LINQ alternative to this approach: rainbowArray.Where(databaseArray.Contains)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.